I am working with an array of nested objects and need to extract the value of a specific key property. Currently, I am using a for loop and checking for the existence of children property, but I feel there might be a more optimal way to accomplish this task. Below is the array of object data that I am working with, where I need to retrieve the text for the id 121.
var abc = [
{
id: 1,
text: 'One',
children: [
{id: 11, text: 'One One'},
{id: 12, text: 'One two',
children: [ {id: 121, text: 'one two one'} ]}
]
},
{
id: 2,
text: 'two'
}
];
The approach I have implemented seems to be very specific to this particular problem. Here is my current code snippet:
for(var val of abc){
if(val.id == 121){
console.log('in first loop',val.text);
break;
}
if(Array.isArray(val.children)){
for(var childVal of val.children) {
if(childVal.id == 121){
console.log('in first child', childVal.text);
break;
}
if(Array.isArray(childVal.children)){
for(var nextChild of childVal.children){
if(nextChild.id == 121){
console.log('in next child', nextChild.text);
break;
}
}
}
}
}
}