const dataArr = [
{
"id": 28,
"title": "Free content",
"children": [
{
"id": 29,
"title": "Lorem",
"children": [
{
"id": 32,
"title": "Lorem",
"children": []
},
{
"id": 30,
"title": "Lorem",
"children": []
}
],
},
{
"id": 33,
"title": "Lorem",
"children": [
{
"id": 35,
"title": "Lorem",
"children": []
},
{
"id": 34,
"title": "Lorem",
"children": []
}
],
}
],
}
]
let objID = 29
function test1(arr) {
let res = [];
arr.forEach(item => {
if (item.id === objID) {
Res. push(item)
} else {
test1(item.children)
}
});
console.log('funtion test1', res)
return res
}
console.log('result', test1(dataArr))
result {
"id": 29,
"title": "Lorem",
"children": [
{
"id": 32,
"title": "Lorem",
"children": []
},
{
"id": 30,
"title": "Lorem",
"children": []
}
],
},
function test1(arr)
function test1(arr) {
return arr.reduce((res, item) => {
if (item.id === objID) {
Res. push(item);
} else {
Res. push(...test1(item.children));
}
return res;
}, []);
}
Find more questions by tags RecursionJavaScript