如果要匹配,我想匹配id和parentId,然后添加子元素
ex
let menuItems = [
{
"id": "menu-0",
"title": "Home",
"parentId": "menu-1",
"childCount": 0
},
{
"id": "menu-1",
"title": "About",
"parentId": null,
"childCount": 2
},
{
"id": "menu-3",
"title": "About Sub1",
"parentId": "menu-1",
"childCount": 2
},
{
"id": "menu-5",
"title": "About Sub2",
"parentId": "menu-1",
"childCount": 0
},
{
"id": "menu-4",
"title": "About Sub1 sub1",
"parentId": "menu-3",
"childCount": 0
},
{
"id": "menu-6",
"title": "Contact",
"parentId": null,
"childCount": 2
}
]
<ul>
<li>About
<ul>
<li>
About Sub1
</li>
</ul>
</li>
<li>
Contact
</li>
</ul>
data[i].id == data[i].parentId
但返回false
答案 0 :(得分:0)
您正在比较同一对象的id和parentId,这就是为什么它总是返回false的原因。我不确定您要达到的目标,但是如果您要计算childCount,可以执行以下操作:
menuItems.forEach( parent => parent.childCount = menuItems.filter( child => parent.id === child.parentId).length);
答案 1 :(得分:0)
enter code here{ for (let i = 0; i < data.length; i++) {
for (let j = 0; j < data.length; j++) {
if(data[i].id == data[j].parentId){
console.log(data[i]);
}
}
}
output
{id: "menu-1", title: "About", parentId: null, childCount: 2}
{id: "menu-1", title: "About", parentId: null, childCount: 2}
{id: "menu-3", title: "About Sub1", parentId: "menu-1", childCount: 2}
}