Use recursion to achieve 10000 data

code

const initTreeData = (data = [], initAttributes = {}) = > {
  const Attributes = {
    parentId: 'parentId'.title: 'title'.value: 'id'.rootId: 0.id: 'id'};constattributes = { ... Attributes, ... (initAttributes || {}) };const resData = data || [];
  const tree = [];
  for (let i = 0; i < resData.length; i += 1) {
    if (resData[i][attributes.parentId] === attributes.rootId) {
      constobj = { ... resData[i],children: [],}; tree.push(obj); resData.splice(i,1);
      i -= 1;
    }
  }
  run(tree);
  function run(chiArr = []) {
    if(resData.length ! = =0) {
      for (let i = 0; i < chiArr.length; i += 1) {
        for (let j = 0; j < resData.length; j += 1) {
          if (chiArr[i][attributes.id] === resData[j][attributes.parentId]) {
            constobj = { ... resData[j],children: [],}; chiArr[i].children.push(obj); resData.splice(j,1);
            j -= 1; } } run(chiArr[i].children); }}}return tree;
};

console.time("start")
let arr = []
for (let i = 1; i < 10001; i++) {
  arr.push({
    id: i, title: 'department' + i, parentId: i < 11 ? 0 : i - 10.key: i
  })
}
const treeData = initTreeData(arr)
console.log(treeData)
console.timeEnd("start") // Start: 901.011962890625 ms
Copy the code

Use the Tree component of ANTD to see the effect, as shown in the figure:

No recursive implementation

code

const initTreeData2 = (data = []) => { const resDta = [] const resMap = {} for (const item of data) { if (! resMap[item.id]) { item.children = [] resMap[item.id] = item } if (item.parentId === 0) { resDta.push(resMap[item.id]) }  else { if (resMap[item.parentId]) { resMap[item.parentId].children.push(item) } } } return resDta } console.time("start") let arr = [] for (let i = 1; i < 10001; I ++) {arr.push({id: I, title: 'branch' + I, parentId: I < 11? 0 : i - 10, key: i }) } const treeData = initTreeData2(arr) console.log(treeData) console.timeEnd("start") // start: 8.51611328125 msCopy the code

Use the Tree component of ANTD to see the effect, as shown in the figure:

Train of thought

The Map structure is used to store the data, and the reference of the object is used to update the data, which reduces the traversal time and achieves the ultimate goal of optimization