gpt4 book ai didi

javascript - 如何根据属性筛选和排列对象数组

转载 作者:行者123 更新时间:2023-11-30 17:33:35 25 4
gpt4 key购买 nike

我有项目的 JSON 数组:

var items = [
{
Id: "c1",
config:{
url:"/c1",
content: "c1 content",
parentId: "p1",
parentUrl: "/p1",
parentContent: "p1 content",
}
},
{
Id: "c2",
config:{
url:"/c2",
content: "c2 content",
parentId: "p1",
parentUrl: "/p1",
parentContent: "p1 content",
}
},
{
Id: "c3",
config:{
url:"/c3",
content: "c3 content"
}
},
]

结果应该是这样的:

var items = [
{
Id: "p1",
config:{
url:"/p1",
content: "p1 content"
},children:[
{
Id: "c1",
config:{
url:"/c1",
content: "c1 content"
}
},{
Id: "c2",
config:{
url:"/c2",
content: "c2 content"
}
},
]
},
{
Id: "c3",
config:{
url:"/c3",
content: "c3 content"
}
},
]

如果一个对象有父类属性,它们应该被包裹在父类的子类属性中。我发现很难转换它。谁能帮我解决这个问题?谢谢。

最佳答案

此代码未经测试,但希望对您有所帮助:

var new_items = [];

for(i in items) {
var id = items[i].config.parentId;
if(id) {
if(!(parent = get_parent(id))) { // If the new list does not contain the parent...
parent = {Id: id, config: {
url: items[i].config.parentUrl,
content: items[i].config.parentContent,
//... The parent attributes
}, children: []};
}
parent.children.push({/* The child object attributes*/});

}
}

function get_parent(id) {
for(ni in new_itmes) {
if(new_items[ni].Id == id) return new_items[ni];
}
return false;
}

关于javascript - 如何根据属性筛选和排列对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22491084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com