我试图找到确切的位置并访问对象的超级嵌套数组的所有属性。
我正在努力创建一个函数,如果我给定索引号作为输入参数,则应该给我它在数组中的位置,并返回所有属性。
这是对象的示例数组
我也同意ES6及以上版本的解决方案
{
"name": "branch 1",
"index": 1,
"children": [{
"name": "sub child 1",
"index": 2,
"children": [{
"name": "subx2 child 1",
"index": 3,
"children": [{
"name": "subx3 child 1",
"index": 4,
"children": [{
"name": "subx4 child 1",
"index": 21
},
{
"name": "subx4 child 2",
"index": 18
}
]
},
{
"name": "subx3 child 2",
"index": 6,
"children": [{
"name": "subx4 child 1",
"index": 7
},
{
"name": "subx4 child 2",
"index": 21
}
]
},
{
"name": "subx3 child 3",
"index": 22
}
]
}]
},
{
"name": "sub child 2",
"index": 28
}
]
}
是的,我知道这个json对象足够吓人,无法花费时间来解决。任何帮助都非常有用。
例如,如果我的函数名称是 findChildIndex(22),则应该返回类似 x.children [0] .children [0] .children [2]
谢谢!
答案 0 :(得分:3)
您可以递归地收集children
数组中通往目标索引的索引:
function findIndexNested(data, index) {
if (data.index === index) return [];
let result;
const i = (data.children || []).findIndex(child => {
return result = findIndexNested(child, index)
});
if (result) return [i, ...result];
}
function findByPath(data, path) {
for (let i of path) data = data.children[i];
return data
}
// Sample data
const data = {"name": "branch 1","index": 1,"children": [{"name": "sub child 1","index": 2,"children": [{"name": "subx2 child 1","index": 3,"children": [{"name": "subx3 child 1","index": 4,"children": [{"name": "subx4 child 1","index": 21},{"name": "subx4 child 2","index": 18}]},{"name": "subx3 child 2","index": 6,"children": [{"name": "subx4 child 1","index": 7},{"name": "subx4 child 2","index": 21}]},{"name": "subx3 child 3","index": 22}]}]},{"name": "sub child 2","index": 28}]}
const index = 22
const result = findIndexNested(data, index);
console.log("Found index " + index + " via these child indexes: " + result);
console.log("The object is", findByPath(data, result));
答案 1 :(得分:2)
您可以使用递归并检查元素children
是否存在,可以使用for
循环遍历所有children
并递归地应用每个子元素的功能
const obj = {
"name": "branch 1",
"index": 1,
"children": [{
"name": "sub child 1",
"index": 2,
"children": [{
"name": "subx2 child 1",
"index": 3,
"children": [{
"name": "subx3 child 1",
"index": 4,
"children": [{
"name": "subx4 child 1",
"index": 21
},
{
"name": "subx4 child 2",
"index": 18
}
]
},
{
"name": "subx3 child 2",
"index": 6,
"children": [{
"name": "subx4 child 1",
"index": 7
},
{
"name": "subx4 child 2",
"index": 21
}
]
},
{
"name": "subx3 child 3",
"index": 22
}
]
}]
},
{
"name": "sub child 2",
"index": 28
}
]
}
function find(obj,index){
if(obj.children){
for(let i = 0;i<obj.children.length;i++){
let x = find(obj.children[i],index);
if(x) return {...x,pos:i};
}
}
return obj.index === index ? obj : false;
}
console.log(find(obj,21))
答案 2 :(得分:1)
如果我正确回答了您的问题,则可以执行以下操作:
const func=(obj,index, nested=0)=>{
return Obj.index===index ? {obj, nested} : func(obj.children,index, nested+1)
}