I have array of nested object. I have to check the property of key object and return its value. I have done it using the for loop and checking with children property exist or not. But I think it is not optimal way to do it. what will be most optimal way to do it. Here is the code array of object data. I have to get 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'
}
];
My approach is very specific to this problem. Here it is
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;
}
}
}
}
}
}