为了账号安全,请及时绑定邮箱和手机立即绑定

重组对象数组的最佳方法

重组对象数组的最佳方法

饮歌长啸 2022-12-22 15:45:05
我需要通过 id 将链接对象的数组重组为一个树对象。深度级别未知,因此我认为应该递归完成。什么是最有效的方法?我有下一个对象数组:const arrObj = [  {    "id": 1,    "children": [      {        "id": 2      },      {        "id": 3      }    ]  },  {    "id": 2,    "children": [      {        "id": 4      },      {        "id": 5      }    ]  },  {    "id": 3,    "children": [      {        "id": 6      }    ]  },  {    "id": 4  }]我想重组只有一个对象,比如一棵树:const treeObj = {  "id": 1,  "children": [    {      "id": 2,      "children": [        {          "id": 4        },        {          "id": 5        }      ]    },    {      "id": 3,      "children": [        {          "id": 6        }      ]    }  ]}每个对象都有其他许多属性。
查看完整描述

1 回答

?
慕斯709654

TA贡献1840条经验 获得超5个赞

您可以对所有children.


const arrObj = [ { "id": 1, "children": [ { "id": 2 }, { "id": 3 } ] }, { "id": 2, "children": [ { "id": 4 }, { "id": 5 } ] }, { "id": 3, "children": [ { "id": 6 } ] }, { "id": 4 } ];

const res = arrObj[0];//assuming the first element is the root

res.children = res.children.map(function getChildren(obj){

  const child = arrObj.find(x => x.id === obj.id);

  if(child?.children) child.children = child.children.map(getChildren);

  return child || obj;

});

console.log(res);


查看完整回答
反对 回复 2022-12-22
  • 1 回答
  • 0 关注
  • 116 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号