亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

重組對象數組的最佳方法

重組對象數組的最佳方法

飲歌長嘯 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 關注
  • 140 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號