gpt4 book ai didi

javascript - 遍历一个json树结构并将所有节点添加到一个列表中

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

所以我有一个 json 对象,我想遍历并将所有节点添加到线性列表中。下面是我的 json

    [{ "name" : "Joe", "age" : "21", "children" : [
{ "name" : "Smith", "age" : "42", "children" : [] },
{ "name" : "Gary", "age" : "21", "children" : [
{ "name" : "Jenifer", "age" : "23", "children" : [
{ "name" : "Dani", "age" : "32", "children" : [] },
{ "name" : "Max", "age" : "34", "children" : [] }
]}
]}
]},
{ "name" : "Albert", "age" : "33", "children" : [] },
{ "name" : "Ron", "age" : "29", "children" : [] }
];

我想创建树中所有对象的列表,对象需要像这样:
{ "name": "Joe", "age": "21"}

最佳答案

使用递归函数可以轻松遍历和展平数组。这是一个示例算法:

function flatten(items, result = []) {
if (items.length) {
var item = items.shift();
result.push(item);

if (item.children && item.children.length) {
result = flatten(item.children, result);
}

return flatten(items, result);
} else {
return result;
}
}

var people = [{
"name": "Joe",
"age": "21",
"children": [{
"name": "Smith",
"age": "42",
"children": []
}, {
"name": "Gary",
"age": "21",
"children": [{
"name": "Jenifer",
"age": "23",
"children": [{
"name": "Dani",
"age": "32",
"children": []
}, {
"name": "Max",
"age": "34",
"children": []
}]
}]
}]
}, {
"name": "Albert",
"age": "33",
"children": []
}, {
"name": "Ron",
"age": "29",
"children": []
}];

console.log(flatten(people));

关于javascript - 遍历一个json树结构并将所有节点添加到一个列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38626617/

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