I'm trying to pass a key to a recursive function and find and return that object with that key.
This is the array that I like to search into
const treeData = [
{
title: 'parent 1',
key: '0-0',
children: [
{
title: 'parent 1-0',
key: '0-0-0',
disabled: true,
children: [
{
title: 'leafffff',
key: '0-0-0-0',
disableCheckbox: true,
},
{
title: 'leaf',
key: '0-0-0-1',
},
],
},
],
},
];
And this is my current function
function findNode(x, key) {
if (x.key === key)
return x
else if (Array.isArray(x)) {
return x.map(item => {
const r = findNode(item, key)
if (r) return r
if (item.children)
return findNode(item.children, key)
})
}
}
Live example:
const treeData = [ { title: 'parent 1', key: '0-0', children: [ { title: 'parent 1-0', key: '0-0-0', disabled: true, children: [ { title: 'leafffff', key: '0-0-0-0', disableCheckbox: true, }, { title: 'leaf', key: '0-0-0-1', }, ], }, ], }, ];
function findNode(x, key) {
if (x.key === key)
return x
else if (Array.isArray(x)) {
return x.map(item => {
const r = findNode(item, key)
if (r) return r
if (item.children)
return findNode(item.children, key)
})
}
}
const node = findNode(treeData, '0-0-0-1')
console.log(node)
Using this function I can find the result but is not in the current format. I like to get a single object but gives me nested array with that object in the most nested child