当前位置:网站首页>JS to convert array to tree data

JS to convert array to tree data

2022-07-07 12:29:00 Xiaoding Chong duck!

Subject requirements :

Convert the following array into a tree structure :

const nodes = [
  { id: 3, name: ' node C', parentId: 1 },
  { id: 6, name: ' node F', parentId: 3 },
  { id: 0, name: 'root', parentId: null },
  { id: 1, name: ' node A', parentId: 0 },
  { id: 8, name: ' node H', parentId: 4 },
  { id: 4, name: ' node D', parentId: 1 },
  { id: 2, name: ' node B', parentId: 0 },
  { id: 5, name: ' node E', parentId: 2 },
  { id: 7, name: ' node G', parentId: 2 },
  { id: 9, name: ' node I', parentId: 5 }
];

The tree structure is :

Ideas :

1、 With id by key, Building an object obj, Used to find parent

2、 Iterate over the original array , adopt parentId from obj Parent node found in , Then insert yourself into the parent node children in

notes : Pay attention here , Object is a reference type , therefore map The object inside changes , The same node object in the corresponding original array will also change .

Code :

function convert(data) {
  let result;
  let map = {};
  data.forEach(item => {
      map[item.id] = item;
  });
  // console.log(map);
  data.forEach(item => {
      // item.pid  by 0 when   return underfined
      let parent = map[item.parentId];
      if (parent) {
        (parent.children || (parent.children = [])).push(item);
      } else {
          //  here push Of item yes pid by 0 The data of 
          result = item;
      }
  });
  return result;
}

Miao !

原网站

版权声明
本文为[Xiaoding Chong duck!]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130617454472.html