js数组中将有父子关系的平行数组转换成树形数据

2024年07月24日 建站教程

let data = [
{id: 1, text: '清北', parentId: 0},
{id: 2, text: '浙京', parentId: 2},
{id: 3, text: '浙京', parentId: 1},
{id: 4, text: '浙京', parentId: 3},
{id: 5, text: '清北', parentId: 1},
{id: 6, text: '浙京', parentId: 0},
];
data.forEach(ele => {
  let parentId = ele.parentId;
  if (parentId === 0) {
    //parentId===0是根路径
  } else {
    //其它的扔到根路径child下面数组中.
    data.forEach(d => {
      if (d.id === parentId) {
        let childArray = d.child;
        if (!childArray) {
          childArray = []
        }
        childArray.push(ele);
        d.child = childArray;
      }
    })
  }
});
//去除重复元素
data = data.filter(ele => ele.parentId === 0);
console.log('输出结果: ', data);

//输出结果
//0: {id: 1, text: '清北', parentId: 0, child: Array(2)}
//1: {id: 6, text: '浙京', parentId: 0}

本文链接:http://so.lmcjl.com/news/9078/

展开阅读全文
相关内容