我有这样一个数组:
parent = [
{'id':'id_1','level':'1-1','children':['id':'id_1','level':'1-1-0','children':[........]},
{'id':'id_2','level':'2-2','children':['id':'id_1','level':'2-1-0','children':[........]}
]如何获得与子数组对象条件匹配的父数组索引?
例如,:
If (level == '2-1-0') 产出:1
预期行为:
它应该返回1,因为父数组的第1‘索引中存在2-1-0级别。
注意:,我尝试了如下
var index = parent .findIndex(data => data.level== result.level);它不会检查子数组对象。
发布于 2022-01-06 11:33:54
你需要递归
const findItemNested = (arr, level, nestingKey) => (
arr.reduce((a, item, index) => {
if (a) return a;
if (item.level === level) return index;
if (item[nestingKey]) return findItemNested(item[nestingKey], level, nestingKey)
}, null)
);
const testArr = [
{
'id':'id_1',
'level':'1-1',
'children':[
{'id':'id_1'},
{'level':'1-1-0'},
{'children':[]}
]
},
{'id':'id_2','level':'2-2','children':[{'id':'id_1'},{'level':'2-1-0'},{'children':[]}]}
];
const res = findItemNested(testArr, '2-1-0', "children");
console.log(res) // 1发布于 2022-01-06 11:05:31
您提供的数组是错误的,但是我认为您需要这样的东西:
const parent = [
{'id':'id_1','level':'1-1','children':[{'id':'id_1','level':'1-1-0'}]},
{'id':'id_2','level':'2-2','children':[{'id':'id_1','level':'2-1-0'}]}
]
const index = parent.findIndex(p => p.children.find(c => c.level === '2-1-0') !== undefined);
console.log(index);在“2-1-0”的位置,你应该把索引放在你想要检查的地方。
发布于 2022-01-06 11:18:31
这是一个递归问题,可能会导致大数组的堆栈失效。
脚本首先遍历树的深度,并且可以进行优化以检测请求的级别深度,并且只检查该级别,从而提高了性能。
var weirdProblem = level => (carry, current, idx) => {
// bail if already found
if (carry > -1) {
return carry;
}
// check current item's children and return current idx if matching
if (current.children.some(child => child.level === level)) {
return idx;
}
// traverse current item's children
return current.children.reduce(weirdProblem(level), -1);
};
var index = parent.reduce(weirdProblem('2-1-0'), -1);没有测试脚本。
https://stackoverflow.com/questions/70606077
复制相似问题