javascript 一维数组转树结构

实现将JS的一维数组转换成树结构的方法有多种,下面列举了三种常见的实现方式:

方法一:递归构建树结构

function convertToTree(arr, idProp, parentProp, childProp) {
  // 将一维数组转换为map,根据idProp来索引元素
  const map = {};
  arr.forEach(item => {
    map[item[idProp]] = item;
  });
 
  // 递归构建树结构
  const tree = [];
  arr.forEach(item => {
    const parent = map[item[parentProp]];
    if (parent) {
      parent[childProp] = parent[childProp] || [];
      parent[childProp].push(item);
    } else {
      tree.push(item);
    }
  });
 
  return tree;
}
const arr = [
  { id: 1, name: '节点1', parentId: null },
  { id: 2, name: '节点2', parentId: 1 },
  { id: 3, name: '节点3', parentId: 1 },
  { id: 4, name: '节点4', parentId: 3 },
  { id: 5, name: '节点5', parentId: 2 },
  { id: 6, name: '节点6', parentId: null },
];
 
const tree = convertToTree(arr, 'id', 'parentId', 'children');
console.log(tree);

方法二:使用迭代方式构建树结构

function convertToTree(arr, idProp, parentProp, childProp) {
  // 将一维数组转换为map,根据idProp来索引元素
  const map = {};
  arr.forEach(item => {
    map[item[idProp]] = item;
  });
 
  // 迭代构建树结构
  const tree = [];
  arr.forEach(item => {
    const parent = map[item[parentProp]];
    if (parent) {
      parent[childProp] = parent[childProp] || [];
      parent[childProp].push(item);
    } else {
      tree.push(item);
    }
  });
 
  return tree;
}
const arr = [
  { id: 1, name: '节点1', parentId: null },
  { id: 2, name: '节点2', parentId: 1 },
  { id: 3, name: '节点3', parentId: 1 },
  { id: 4, name: '节点4', parentId: 3 },
  { id: 5, name: '节点5', parentId: 2 },
  { id: 6, name: '节点6', parentId: null },
];
 
const tree = convertToTree(arr, 'id', 'parentId', 'children');
console.log(tree);

方法三:使用深度优先搜索(DFS)构建树结构

function convertToTree(arr, idProp, parentProp, childProp) {
  // 将一维数组转换为map,根据idProp来索引元素
  const map = {};
  arr.forEach(item => {
    map[item[idProp]] = item;
  });
 
  const stack = [];
  const tree = [];
 
  // 进行深度优先搜索
  arr.forEach(item => {
    const parent = map[item[parentProp]];
    if (parent) {
      parent[childProp] = parent[childProp] || [];
      parent[childProp].push(item);
    } else {
      tree.push(item);
      stack.push(item);
    }
  });
 
  while (stack.length > 0) {
    const node = stack.pop();
    const children = node[childProp];
    if (children) {
      children.forEach(child => {
        stack.push(child);
        child[childProp] = child[childProp] || [];
      });
    }
  }
 
  return tree;
}
const arr = [
  { id: 1, name: '节点1', parentId: null },
  { id: 2, name: '节点2', parentId: 1 },
  { id: 3, name: '节点3', parentId: 1 },
  { id: 4, name: '节点4', parentId: 3 },
  { id: 5, name: '节点5', parentId: 2 },
  { id: 6, name: '节点6', parentId: null },
];
 
const tree = convertToTree(arr, 'id', 'parentId', 'children');
console.log(tree);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值