【JS面试题】将数据转换树形结构

复盘一道面试中写的不好的场景题

题目描述

写一个函数flatToTree(),将扁平化数据转成json树形结构
实例输入

let flatArr = [
  {id: 1, title: "A", parent_id: -1},
  {id: 2, title: 'B', parent_id: -1},
  {id: 3, title: 'C', parent_id: 2},
  {id: 4, title: 'D', parent_id: 3},
]

(元素自身id唯一,pid是父节点。父节点为-1的为根节点,可以有多个根节点)

思路

通过遍历完成两个任务
1、创建一个新的带children的结构
2、父节点在map有key值对应,则在父节点的children添加新元素
没有父节点,在根节点添加父节点

代码

function ArrToTree(arr) {
  let tree = [];
  const map = {};
  for (let item of arr) {
    map[item.id] = {
      ...item,
      children: [],
    };
  }
  for (let item of arr) {
    let newItem = map[item.id];
    if (map[item.pid]) {
      let parent = map[item.pid];
      parent.children.push(newItem);
    } else {
      tree.push(newItem);
    }
  }
  return tree;
}

输出结果

  [
    { id: 1, title: 'A', pid: -1, children: [] },
    { id: 2, title: 'B', pid: -1, children: [ 
      { id: 3, title: 'C', pid: 2, children: [
        { id: 4, title: 'D', pid: 3, children: [] }] 
      } ] 
    }
  ]
  
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值