您好我有一个嵌套的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
}]
]
感谢任何帮助。
答案 0 :(得分:0)
您可以将路径存储到leafes并将路径推送到结果集。
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; }