I need to find name in a deeply nested object by id. Maybe lodash will help? What is the cleanest way to do it, If I don't know how many nested object there will be in my array?
Here's example array:
let x = [
{
'id': '1',
'name': 'name1',
'children': []
},
{
'id': '2',
'name': 'name2',
'children': [{
'id': '2.1',
'name': 'name2.1',
'children': []
},
{
'id': '2.2',
'name': 'name2.2',
'children': [{
'id': '2.2.1',
'name': 'name2.2.1'
},
{
'id': '2.2.2',
'name': 'name2.2.2'
}
]
}
]
},
{
'id': '3',
'name': 'name3',
'children': [{
'id': '3.1',
'name': 'name3.1',
'children': []
},
{
'id': '3.2',
'name': 'name3.2',
'children': []
}
]
}
];
For example I have id "2.2" and i need name of it. Thanks
from your data here is a solution that can help you achieve that easily
function findById(array, id) {
for (const item of array) {
if (item.id === id) return item;
if (item.children?.length) {
const innerResult = findById(item.children, id);
if (innerResult) return innerResult;
}
}
}
const foundItem = findById(x, "2.2");
console.log(foundItem);
/*
The result obtained here is: {id: '2.2', name: 'name2.2', children: Array(2)}
*/