对象数组添加属性后插入子元素

题目

给出一个数组:

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},
  ]

其中pid表示此元素对象是id为对应值所在对象的children中的一员,如下所示:

// 这里仅仅展示了第一个元素的样子
target = [
{
  id: 1,
  name: '部门1',
  pid: 0,
  children: [
    { id: 2, name: '部门2', pid: 1, children: [] },
    { id: 3, name: '部门3', pid: 1, children: [Array] }
  ]
}
]
暴力解法
let 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},
  ]
  function getTarget (arr) {
      let target = [...arr];
      target.map(x => {x.children = []});
      for(let i =0; i < target.length - 1; i++){
          for(let j = i + 1; j < target.length; j++){
              if(target[i].id === target[j].pid){
                  target[i].children.push(target[j]);
              }
          }
      }
      return target;
  }
  console.log(getTarget(arr)[0]);
优化解法

按照for循环遍历原数组,取出其中的pid,其中pid的值对应着id,由于数据可能是乱序的,所以可以使用hashmap先将id的值作为键值,索引作为值存储起来,再对pid进行遍历判断。

let 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},
  ]
  function getTarget (arr) {
      let target = [...arr];
      let map = new Map();
      for(let i = 0; i < target.length; i++){
          target[i].children = [];
          map.set(target[i].id, i);
      }
      for(let i =0; i < target.length; i++){
          let temp = target[i].pid;
          if(map.has(temp)){
              let ans = map.get(temp);
              target[ans].children.push(target[i]);
          } else continue;
      }
      return target;
  }
  console.log(getTarget(arr)[0]);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

努力不熬夜的小喵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值