js 一维数组转换为树形结构


测试数据:

const list = [
  { id: 1, pid: 0, name: '四川' },
  { id: 2, pid: 1, name: '成都' },
  { id: 3, pid: 1, name: '宜宾' },
  { id: 4, pid: 1, name: '绵阳' },
  { id: 5, pid: 1, name: '德阳' },
  { id: 6, pid: 2, name: '高新区' },
  { id: 7, pid: 2, name: '武侯区' },
  { id: 8, pid: 3, name: '翠屏区' }
];

方法一: 使用递归进行转换. 传入数组,根节点父级id,返回一个树结构的数组.

const arrayToTree = (arr, pid) => {
  return arr.reduce((res, current) => {
    if (current['pid'] === pid) {
      current.children = arrayToTree(arr, current['id']);
      return res.concat(current);
    }
    return res;
  }, []);
};
console.log(arrayToTree(list, 0))

方法二:hash表 + 引用关系.传入数组,根节点id ,返回一个树结构对象

const arrayToTree = (arr, rootId) => {
  const map = {};
  for (const iterator of arr) {
    map[iterator['id']] = iterator;
  }
  for (const iterator of arr) {
    const key = iterator['pid'];
    if (!(key in map)) continue;
    map[key].children = (map[key].children || []).concat(iterator);
  }
  return map[rootId];
};
console.log(arrayToTree(list, 1));


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM