I'm trying to find/ extract a specific object in a nested hierarchy. when the entity is found I console.log it and then return it. the log is the correct object but the function still returns undefined.
any solutions? I've tried with a map, reduce, and a classic for loop and still gets undefined back.
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)