gpt4 book ai didi

javascript - 比较键后如何将对象列表转换为嵌套对象

转载 作者:行者123 更新时间:2023-11-30 14:00:11 24 4
gpt4 key购买 nike

目的:根据对象的父值将对象列表放入嵌套对象中。

我的 json 数据如下:

"data": [
{
"id": "coding-825x500",
"source": {
"information": {
"fileid": "coding-825x500",
"filesize": 67340
},
**"dependent": "d1bc270d"**
}
},
{
"id": "d1bc270d",
"source": {
"information": {
"fileid": "d1bc270d",
"filesize": 193
},
"dependent": "parent"
}
},
{
"id": "1_iwPLQ",
"source": {
"information": {
"fileid": "1_iwPLQ",
"filesize": 580969
},
"dependent": "d1bc270d"
}
},
{
"id": "coding-825",
"source": {
"information": {
"fileid": "coding-825",
"filesize": 67340
},
"dependent": null
}
}
]
}

在每个对象中我们都有id & dependent

{ 
"id": A
"dependent":parent
},
{
"id": B
"dependent":A
},
{
"id": C
"dependent":A
},
{
"id": D
"dependent":null
}

如果 id 等于依赖 id,那么它应该是 child ,如果依赖是父,那么 id == dependent 必须在这个下面,如果 dependent 是 null 那么它也是没有 child 的 parent 。

下面我使用了过滤器,但后来我不确定如何继续和创建嵌套对象。

let info = this.dynamic.data.filter((val)=>{
console.log(val.id, ":::" ,val.source.dependent);
})

Stackblitz => https://stackblitz.com/edit/angular-zvcea7

期望的输出:所有子对象都应该在父对象下以设置嵌套数据,表格可能像下面的格式。

  {

"id": "A",
"dependent":parent

"nested":[

{

"id":"B",

"dependent":"A"

},
{

"id":"c",

"dependent":"A"

},



]

},
{

"id": "c",
"dependent":null


}

最佳答案

您可以构建一棵树并为具有'parent' 的节点使用统一的null 值。

这种方法也适用于未排序的数据。

var data = [{ id: 'A', dependent: 'parent' }, { id: 'B', dependent: 'A' }, { id: 'D', dependent: null }, { id: 'C', dependent: 'A' }],
tree = function (data) {
var t = {};
data.forEach(o => {
var parent = o.dependent === 'parent' ? null : o.dependent;
Object.assign(t[o.id] = t[o.id] || {}, o);
t[parent] = t[parent] || {};
t[parent].nested = t[parent].nested || [];
t[parent].nested.push(t[o.id]);
});
return t.null.nested;
}(data);

console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }

用第一个数据集。 dependent 属性嵌套在另一个对象中。

var data = [{ id: "coding-825x500", source: { information: { fileid: "coding-825x500", filesize: 67340 }, dependent: "d1bc270d" } }, { id: "d1bc270d", source: { information: { fileid: "d1bc270d", filesize: 193 }, dependent: "parent" } }, { id: "1_iwPLQ", source: { information: { fileid: "1_iwPLQ", filesize: 580969 }, dependent: "d1bc270d" } }, { id: "coding-825", source: { information: { fileid: "coding-825", filesize: 67340 }, dependent: null } }],
tree = function (data) {
var t = {};
data.forEach(o => {
var parent = o.source.dependent === 'parent' ? null : o.source.dependent;
Object.assign(t[o.id] = t[o.id] || {}, o);
t[parent] = t[parent] || { id: parent, source: null };
t[parent].nested = t[parent].nested || [];
t[parent].nested.push(t[o.id]);
});
return t.null.nested;
}(data);

console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 比较键后如何将对象列表转换为嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56438450/

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