如题,但我遇到了一个问题!
我想创建 getParentId(array, id)
函数。
此函数通过子id获取父id。
const array = [{
id: 1,
title: 'hello',
children: [{
id: 3,
title: 'hello',
children: [{
id: 4,
title:'hello',
children: [
{ id: 5, title: 'hello'},
{ id: 6, title: 'hello'}
]
},
{
id: 7,
title: 'hello'
}]
}]
},
{
id: 2,
title: 'hello',
children: [
{ id: 8, title: 'hello'}
]
}]
- 这个数组可以无限嵌套
预期结果:
getParentId(array, 3) -> 1
getParentId(array, 5) -> 4
getParentId(array, 6) -> 4
getParentId(array, 8) -> 2
getParentId(array, 2) -> null
如果你能给我发送信息,我将不胜感激。
最佳答案
您可以通过迭代实际数组及其子数组并在找到 id
时停止来采用递归方法。
function getParentId(array, id, parentId = null) {
return array.some(o => {
if (o.id === id) return true;
const temp = getParentId(o.children || [], id, o.id);
if (temp !== null) {
parentId = temp;
return true;
}
})
? parentId
: null;
}
const array = [{ id: 1, title: 'hello', children: [{ id: 3, title: 'hello', children: [{ id: 4, title:'hello', children: [{ id: 5, title: 'hello' }, { id: 6, title: 'hello' }] }, { id: 7, title: 'hello' }] }] }, { id: 2, title: 'hello', children: [{ id: 8, title: 'hello' }] }];
console.log(getParentId(array, 3)); // 1
console.log(getParentId(array, 5)); // 4
console.log(getParentId(array, 6)); // 4
console.log(getParentId(array, 8)); // 2
console.log(getParentId(array, 2)); // null
console.log(getParentId(array, 7)); // 3
console.log(getParentId(array, 4)); // 3
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 如何在 JavaScript 中获取无限嵌套数组中的父 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53896719/