gpt4 book ai didi

javascript - 迭代无限嵌套的 json 结构

转载 作者:行者123 更新时间:2023-11-28 04:07:51 27 4
gpt4 key购买 nike

嗨,我有一个嵌套的 JSON,也可以具有无限的层次结构。下面是 JSON 的结构 -

[{
"name": "Main",
"leaf": false,
"id": 12,
"ParentId": null,
"children": [{
"name": "Sub Main 1",
"leaf": false,
"id": 13,
"ParentId": 12,
"children": [{
"name": "child 1",
"id": 15,
"ParentId": 13,
"leaf": true
}, {
"name": "child 2",
"id": 16,
"ParentId": 13,
"leaf": true
}]
}, {
"name": "Sub Main 2",
"leaf": false,
"id": 14,
"ParentId": 12,
"children": [{
"name": "child 1",
"id": 17,
"ParentId": 14,
"leaf": true
}, {
"name": "child 2",
"id": 18,
"ParentId": 14,
"leaf": true
}]
}]
}]

我希望输出为 -

[
[{
"name": "Main",
"leaf": false,
"id": 12,
"ParentId": null,
}, {
"name": "Sub Main 1",
"leaf": false,
"id": 13,
"ParentId": 12
}, {
"name": "child 1",
"id": 15,
"ParentId": 13,
"leaf": true
}],
[{
"name": "Main",
"leaf": false,
"id": 12,
"ParentId": null,
}, {
"name": "Sub Main 1",
"leaf": false,
"id": 13,
"ParentId": 12
}, {
"name": "child 2",
"id": 16,
"ParentId": 13,
"leaf": true
}],
[{
"name": "Main",
"leaf": false,
"id": 12,
"ParentId": null,
}, {
"name": "Sub Main 2",
"leaf": false,
"id": 13,
"ParentId": 12
}, {
"name": "child 1",
"id": 15,
"ParentId": 13,
"leaf": true
}],
[{
"name": "Main",
"leaf": false,
"id": 12,
"ParentId": null,
}, {
"name": "Sub Main 2",
"leaf": false,
"id": 13,
"ParentId": 12
}, {
"name": "child 1",
"id": 15,
"ParentId": 13,
"leaf": true
}]
]

感谢任何帮助。

最佳答案

您可以存储叶子的路径,然后将该路径推送到结果集。

function getValues(array) {
var result = [];

array.forEach(function iter(path) {
return function (o) {
var temp = path.concat({ name: o.name, leaf: o.leaf, id: o.id, ParentId: o.ParentId });
if (o.children) {
o.children.forEach(iter(temp));
return;
}
result.push(temp);
};
}([]));

return result;
}

var data = [{ name: "Main", leaf: false, id: 12, ParentId: null, children: [{ name: "Sub Main 1", leaf: false, id: 13, ParentId: 12, children: [{ name: "child 1", id: 15, ParentId: 13, leaf: true }, { name: "child 2", id: 16, ParentId: 13, leaf: true }] }, { name: "Sub Main 2", leaf: false, id: 14, ParentId: 12, children: [{ name: "child 1", id: 17, ParentId: 14, leaf: true }, { name: "child 2", id: 18, ParentId: 14, leaf: true }] }] }],
result = getValues(data);

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

关于javascript - 迭代无限嵌套的 json 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46530219/

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