I am trying to display both parent and child from a Nested JSON data structure. Below is a sample of the JSON data:
[
{
"name": "India",
"children": [
{
"name": "Delhi",
"children": [
{
"name": "South Delhi"
},
{
"name": "North Delhi"
}
]
},
{
"name": "Tamil Nadu",
"children": [
{
"name": "Chennai"
},
{
"name": "Coimbatore"
}
]
}
]
},
{
"name": "America",
"chilren": [
{
"name": "California",
"children": [
{
"name": "Trinity"
},
{
"name": "Yolo"
}
]
},
{
"name": "Florida",
"children": [
{
"name": "Bradford"
},
{
"name": "Calhoun"
}
]
}
]
}
]
In the JSON data above, if I search for the name "Yolo", I expect the result to be America -> California -> Yolo. Can anyone assist me with this?
Below is the code snippet I have written. It currently only displays the child, but I need to also show the parent.
searchRecursive(value) {
for (var i = 0; i < value.length; i++) {
let lowerCaseName = value[i]['name'].toLowerCase();
if (lowerCaseName.includes('yolo')) {
this.searchedItems.push(value[i]);
} else if (value[i]['children']) {
if (value[i]['children'].length > 0) {
this.searchRecursive(value[i]['children']);
}
}
}
return this.searchedItems;
}