Using a tree plug-in for the front end is a very common usage scenario. The data format of the tree plugin is the same as that of any plugin I have used. Whether the data format is assembled by the back end and returned to the front end or assembled by the front end itself is a subject of constant debate between the front end and the back end.
Most of the time the back end will assemble, but some of the front end will do it itself. One of the back ends I worked with earlier came up with the idea that the browser is owned by every user, the server is accessed by all users, and the back-end recursive traversal of the assembled tree data is more costly than the front end processing.
At that time I was speechless, dozens of data assembled into a tree structure of data can be involved in server performance problems, then what can the server do?
I don’t want to discuss whether the front end or the back end will handle this simple thing, as long as we discuss and agree, which side can handle it.
Now there are many methods on the Internet to convert the array to the tree structure, all can get the desired result, today to share this method, I think should be the best performance:
Let arr = [{id: 1, name: '1', pid: 0}, {id: 2, name: '2', pid, 3}, {id: 3, name: '3', pid: 1}, {id: 4, name: '3', pid: 0}, {id: 5, name: 4 ' 'department, pid, 4}, {id: 6, name:' 5 ', pid: 0}, {id: 7, name: '5', pid: 6}, {id: 8, name: Function arrayToTree(data) {let result = []; let itemMap = {}; for (let i = 0; i < data.length; i++) { let item = data[i]; let id = item.id; let pid = item.pid; if(! itemMap[id]){ itemMap[id] = { ... item, children: [] } } let treeItem = itemMap[id]; if(pid === 0){ result.push(treeItem); }else{ if(! itemMap[pid]){ itemMap[pid] = { ... item, children: [] } } itemMap[pid]['children'].push(treeItem); } } return result; } console.log(arrayToTree(arr));Copy the code
Results obtained:
[{" id ": 1," name ":" unit 1 ", "pid" : 0, "children" : [{" id ": 2," name ":" department 2 ", "pid" : 1, "children" : []}, {" id ": Department of 3, "name" : "3", "pid" : 1, "children" : []}}, {" id ": 4," name ":" unit 3 ", "pid" : 0, "children" : [{" id ": 5," name ": "Department of 4", "pid" : 4, "children" :] []}}, {" id ": 6," name ": department of" 5 ", "pid" : 0, "children" : [{" id ": 7," name ": Department of "5", "pid" : 6, "children" : [{" id ": 8," name ": department of" 5 ", "pid" : 7, "children" : []}]}}]]Copy the code
The idea is very simple, maintain a JSON map, each ID has its own children and its own data, put the PID items belonging to this ID into the children array, because the JSON map is all objects, shallow copy, as long as the children array belonging to this object will be the same. You can print an itemMap and see the data for each ID.
Welcome to the Coding personal Note subscription number