具有此JSON有效负载,包含ID,名称和子代数组。在这里,我需要获取所有元素的ID,包括根和所有嵌套的子代。
{
"_id": "-1",
"_name": "root",
"_children": [
{
"_id": "1",
"_name": "Child 1",
"_children": [
{
"_id": "1-1",
"_name": "Child 1-1",
"_children": [
{
"_id": "1-1-1",
"_name": "Child 1-1-1",
"_children": [
]
}
]
},
{
"_id": "1-2",
"_name": "Child 1-2",
"_children": [
]
},
{
"_id": "1-3",
"_name": "Child 1-3",
"_children": [
]
}
]
},
{
"_id": "2",
"_name": "Child 2",
"_children": [
{
"_id": "2-2",
"_name": "Child 2-2",
"_children": [
]
}
]
}
]
}
如何循环遍历以获得所有子代+根的id值。
这是我尝试使用嵌套函数但无法正常工作的内容。
getNestedChildren(arr) {
var out = []
for(var i in arr[0].children) {
out.push(arr[i].id);
if(arr[i].children && arr[i].children.size() > 0) {
var children = this.getNestedChildren(arr[i].children)
}
}
您可以使用递归并通过引用修改“结果数组”。
例如,如果您的嵌套对象存储在变量data
中,则:
function addNestedChildrenToArray(obj, resultArray) {
resultArray.push(obj._id);
obj._children.forEach(child => addNestedChildrenToArray(child, resultArray));
}
const resultArray = [];
addNestedChildrenToArray(data, resultArray);
// resultArray now contains the results
console.log(resultArray);
您可以展平一棵树,然后简单地获取ID。请参见工作示例here
const tree = {
"_id": "-1",
"_name": "root",
"_children": [
// ...
]
}
function flattenTree(tree) {
if (!tree) {
return [];
}
if (tree._children) {
const result = tree._children.reduce((prev, current) => prev.concat(flattenTree(current)), [tree]);
return result;
} else {
return [tree];
}
}
const plain = flattenTree(tree);
const ids = plain.map(value => value._id);