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
You could iterate the array and exit early on find, either by finding the node directly or by finding it by iterating the children.
const
find = (key, array = []) => {
let node;
array.some(object => node = object.key === key
? object
: find(key, object.children)
);
return node;
}
data = [{ 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' }] }] }];
console.log(find('0-0', data));
console.log(find('0-0-0', data));
console.log(find('0-0-0-0', data));
console.log(find('0-0-0-1', data));
.as-console-wrapper { max-height: 100% !important; top: 0; }
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' },
],
},
],
},
];
const findNodeInTree = (tree, key) => {
let result = null;
tree.forEach(node => {
if (node.key === key) {
result = node;
} else if (node.children) {
result = findNodeInTree(node.children, key);
}
});
return result;
}
console.log(findNodeInTree(treeData, '0-0-0-0'));