xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

js convert flat array to tree object All In One

js convert flat array to tree object All In One


const arr = [
  {id: 1, name: '部门1', pid: 0},
  {id: 2, name: '部门2', pid: 1},
  {id: 3, name: '部门3', pid: 1},
  {id: 4, name: '部门4', pid: 3},
  {id: 5, name: '部门5', pid: 4},
];



const arrayToTree = (arr = [], key = 'pid') => {
  let tree = {};
  // 分组
  const map = new Map();
  for (const obj of arr) {
    obj.children = [];
    if(!map.has(obj[key])) {
      map.set(obj[key], [obj]);
    } else {
      const temp = map.get(obj[key]);
      map.set(obj[key], [...temp, obj]);
    }
  }
  // for (const item of arr) {
  //   const id = item.id;
  //   const pid = item.pid;
  //   const temp = map.get(pid);
  //   if(!tree[id]) {
  //     tree[id] = {
  //       ...item,
  //       children: [],
  //     }
  //   } else {
  //     tree.children = [...temp];
  //   }
  // }
  console.log('map =', map);
  console.log('map.size  =', map.size);
  for (const [key, value] of map) {
    // console.log('key, value', key, value);
    const temp = value[0];
    const id = temp.id;
    if(key === 0) {
      tree = temp; 
    } else {
      // 递归
      tree.children = findChildren(map, id);
    }
  }
  console.log('tree =', tree);
  return [tree];
};

const findChildren = (map, id) => {
  let result = [];
  const arr = map.get(id) || [];
  if(arr.length === 1 && arr[0].children.length === 0) {
    result = arr;
  } else {
    // temp;
    for (const obj of arr) {
      obj.children = findChildren(map, obj.id);
      result.push(obj);
    }
  }
  return result;
};

arrayToTree(arr);

/* 

map = Map {
  0 => [ { id: 1, name: '部门1', pid: 0 } ],
  1 => [ { id: 2, name: '部门2', pid: 1 }, { id: 3, name: '部门3', pid: 1 } ],
  3 => [ { id: 4, name: '部门4', pid: 3 } ],
  4 => [ { id: 5, name: '部门5', pid: 4 } ]
}
map.size  = 4

*/

/* 

const obj = {
  1: 1,
  b: 'b',
  3: '3c',
};
for (const [key, value] of Object.entries(obj)) {
  console.log('key, value', key, value);
}

const arr = [1, 'b', '3c']
for (const [index, value] of Object.entries(arr)) {
  console.log('index, value', index, value);
}

// 二维数组
const map = new Map([[1, 1], ['b', 'b'], [3, '3c']]);
for (const item of map) {
  console.log('item', item);
}
 */





refs



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @   xgqfrms  阅读(63)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2021-01-01 js & document.designMode
2021-01-01 js & document.execCommand
2021-01-01 软件考试 2021 All In One
2021-01-01 SSH Keys vs GPG Keys
2019-01-01 钉钉 & URL Scheme & Universal Link & Deep Link All In One
2016-01-01 鸟哥的Linux 私房菜:作者:鸟哥-蔡德明(VBird)个人简要介绍!
2016-01-01 GNU Linux 图像处理程序 GIMP All In One
点击右上角即可分享
微信分享提示