Javascript 将对象推入嵌套在对象数组中的对象数组

Javascript 将对象推入嵌套在对象数组中的对象数组,javascript,node.js,Javascript,Node.js,我试图将值“label”和“link”推送到“data”中的一个对象中,其中目标是id等于另一个对象的“parent”值的对象。这些值应该被推送到匹配目标对象的“children”属性中。这似乎不起作用。有什么建议吗 var data = [ { "id": 0, "label": "example page0", "link": "/apx/...", "icon": "..", "parent": null "children": null

我试图将值“label”和“link”推送到“data”中的一个对象中,其中目标是id等于另一个对象的“parent”值的对象。这些值应该被推送到匹配目标对象的“children”属性中。这似乎不起作用。有什么建议吗

var data = [
  {
    "id": 0,
    "label": "example page0",
    "link": "/apx/...",
    "icon": "..",
    "parent": null
    "children": null
  },
  {
    "id": 1,
    "label": "example page1",
    "link": "/apx/...",
    "icon": "notes",
    "parent": null
    "children": null
  },
  {
    "id": 2,
    "label": "example page2",
    "link": "/apx/....",
    "icon": "...",
    "parent": null
    "children": null
  },
  {
    "id": 3,
    "label": "example subpage3",
    "link": "/apx/....",
    "icon": "...",
    "parent": 2
    "children": null
  },
  {
    "id": 4,
    "label": "example subpage4",
    "link": "/apx/....",
    "icon": "...",
    "parent": 2
    "children": null
  }]

for (let entry of data) {
  if (entry.parent > 0) {
  var index = data.findIndex(x => x.id == entry.parent);
  data[index].children.push({ label: entry.label, link: entry.link })
  }
  }
预期产出:

[
  {
    "id": 0,
    "label": "example page0",
    "link": "/apx/...",
    "icon": "..",
    "parent": null
    "children": null
  },
  {
    "id": 1,
    "label": "example page1",
    "link": "/apx/...",
    "icon": "notes",
    "parent": null
    "children": null
  },
  {
    "id": 2,
    "label": "example page2",
    "link": "/apx/....",
    "icon": "...",
    "parent": null
    "children": [ 
    { "label": "example subpage3", "link": "/apx/...." },
    { "label": "example subpage4", "link": "/apx/...." }
    ]
  }
]

您可以使用
Array.prototype.reduce
实现它。
reduce
将迭代
data
数组,查找具有
parent
属性且不为
null
的元素,并通过使用
id
属性进行搜索,从
data
数组中查找其父元素

现在您需要检查
children
属性是否存在,如果不存在,则需要创建一个新的数组对象并分配给
children
属性,否则只需附加到现有的
children
数组:

const data=[{“id”:0,“label”:“example page0”,“link”:“/apx/”,“parent”:null,“children”:null},{“id”:1,“label”:“example page1”,“link”:“/apx/”,“icon”:“notes”,“parent”:null,“children”:null},{“id”:2,“label”:“example page2”,“link”:“/apx/”,“icon”:“…,“parent”:“parent”:null”,“children“/apx/…”,“icon”:“…”,“parent”:2,“children”:null},{“id”:4,“label”:“example subpage4”,“link”:“/apx/…”,“icon”:“…”,“parent”:2,“children”:null}]
const res=data.reduce((acc,entry,idx,data)=>{
如果(entry.parent>0){
const matchingParent=data.find(e=>e.id==entry.parent);
如果(匹配父项){
常量子项={
标签:entry.label,
链接:entry.link
};
if(匹配父项、子项){
匹配父项.子项.推送(子项)
}否则{
matchingParent.children=[child];
}
}
}否则{
acc.push(入口);
}
返回acc;
}, []);

console.log(res);
工作起来很有魅力。有没有办法不创建数组而修改“data”数组?@mister.cake将新数组重新分配给旧变量
data
比修改源数组更好。但是如果确实需要,我已经更新了答案。