I would like to update the object with values after a recursive search finds a particular node.
Where do I need to add logic to achieve this?
I would like to get the first found object from the nested array of objects and update the data with selected:true
based on the iterations to get the value showTree: true
.
Function:
let findDeep = function(data, label) {
return data.filter(function(e) {
if (e.label.includes(label)) {
data.map(el=> el.selected= "true"); // logic to select the first found value
return e;
}
else if (e.item)
//logic for showTree: true
return findDeep(e.item, label);
});
};
Data:
let testData = [
{
id: 1,
label: 'parent1',
item: [
{
id: 21,
label: 'child1',
item: [
{
id: 211,
label: 'child31',
item: [
{
id: 2111,
label: 'child2211',
item: [
{
id: 21111,
label: 'child22111'
}
]
}
]
},
{
id: 222,
label: 'child32'
}
]
},
{
id: 22,
label: 'child2',
item: [
{
id: 221,
label: 'child421',
item: [
{
id: 2211,
label: 'child2211'
}
]
},
{
id: 222,
label: 'child222'
}
]
}
]
},
{
id: 2,
label: 'parent2',
item: [
{
id: 21,
label: 'child2',
item: [
{
id: 511,
label: 'child51',
item: [
{
id: 5111,
label: 'child5211',
item: [
{
id: 51111,
label: 'child52111'
}
]
}
]
},
{
id: 522,
label: 'child352'
}
]
}
]
}
];
I would like to achieve something in the output
console.log(findDeep(testData, 'child3')[0]);
//output list
[
{
"id":1,
"label":"parent1",
"showTree": true,
"item":[
{
"id":21,
"label":"child1",
"showTree": true,
"item":[
{
"id":211,
"label":"child31",
"selected" true,
"item":[
{
"id":2111,
"label":"child2211",
"item":[
{
"id":21111,
"label":"child22111"
}
]
}
]
},
{
"id":222,
"label":"child32"
}
]
},
{
"id":22,
"label":"child2",
"item":[
{
"id":221,
"label":"child421",
"item":[
{
"id":2211,
"label":"child2211"
}
]
},
{
"id":222,
"label":"child222"
}
]
}
]
},
{
"id":2,
"label":"parent2",
"item":[
{
"id":21,
"label":"child2",
"item":[
{
"id":511,
"label":"child51",
"item":[
{
"id":5111,
"label":"child5211",
"item":[
{
"id":51111,
"label":"child52111"
}
]
}
]
},
{
"id":522,
"label":"child352"
}
]
}
]
}
]
//ouptput selected value
{
"id":211,
"label":"child31",
"selected":true,
"item":[
{
"id":2111,
"label":"child2211",
"item":[
{
"id":21111,
"label":"child22111"
}
]
}
]
}