【发布时间】:2021-01-23 17:26:48
【问题描述】:
我正在尝试在嵌套层次结构中查找/提取特定对象。 当找到实体时,我 console.log 它然后返回它。 日志是正确的对象,但函数仍然返回 undefined。
有什么解决办法吗?我已经尝试过使用 map、reduce 和经典的 for 循环,但仍然返回 undefined。
const hierarchy = {
id: '1',
title: 'root',
children: [
{
id: '2',
title: 'second ab',
children: [
{
id:'999',
title: 'nested child AB',
children: [
{
id:'88888',
title: 'very nested child AB'
}
],
}
],
},
{
id: '3',
title: 'third ab',
children: [
{
id:'444',
title: 'nested child AB',
children: [
{
id:'5555',
title: 'very nested child AB'
}
],
}
],
}
]
}
const findEntityToAddInHierarchy = (entityArr, entityId) => {
return entityArr.forEach(entity => {
if(entity.id === entityId) {
console.log('found and returning', entity)
return entity;
} else {
return entity.children && findEntityToAddInHierarchy(entity.children, entityId)
}
})
}
const result = findEntityToAddInHierarchy([hierarchy], '5555');
console.log('this returns undefined', result)
【问题讨论】:
-
嗨!您可以在问题正文中使用标签指定语言;您还可以通过在代码块中指定语言来添加颜色语法,例如编写 ```javascript insert.code.here() ```
标签: javascript loops recursion undefined hierarchy