I've got problem with my function which doesn't return value and makes it undefined, but still it finds proper value but it 'got lost'. What I'm doing is going trough deeply nested array and looking for parent of element I want to add by the parentId.
const data = [
{ id: '1', parentId: null, title: 'Hi'},
[
{ id: '2', parentId: '1', title: 'Hello'},
{ id: '3', parentId: '2', title: 'Morning'},
[
{ id: '5', parentId: '2', title: 'Bye'},
{ id: '6', parentId: '3', title: 'Hey'},
]
]
]
Here's the function I use to find parent:
findParent(value, data) {
return new Promise((resolve, reject) => {
let parent;
data.map(child => {
if (isArray(child)) {
return findParent(value, child);
} else {
if (child.id === value.parentId) {
return parent = child;
}
}
})
if (parent !== undefined) {
resolve(parent)
} else {
reject(Error('Parent is undefined'))
}
});
}
value passed is something like part of data { id: '2', parentId: '1', title: 'Hello'} for example.
Thanks in advance.
id, and you want to return the parent of the object with thatid?Array.prototype.mapis not intended to make side effects. What you could do is first flattern your array (or convert it to a Map) and then lookup items by id.