We have a JSON file:
var response = {
"Status": "Met",
"Text": "Text1",
"Id": "AAA",
"ContentItems": [
{
"Selected": true,
"Text": "Text2",
"Id": "BBB"
},
{
"Status": "Met",
"Text": "Text3",
"Id": "CCC",
"ContentItems": [
{
"Selected": true,
"Text": "Text5",
"Id": "DDD"
},
{
"Status": "Met",
"Text": "Text6",
"Id": "EEE",
"ContentItems": [
{
"Selected": true,
"Text": "Text7",
"Id": "FFF"
},
{
"Selected": true,
"Text": "Text8",
"Id": "GGG"
},
{
"Status": "Met",
"Text": "Text9",
"Id": "III",
"ContentItems": [
{
"Status": "Met",
"Text": "Text11",
"Id": "JJJ",
"ContentItems": [
{
"Text": "Text12",
"Id": "77"
},
{
"Status": "Met",
"Text": "Text13",
"Id": "10",
"ContentItems": [
{
"Text": "Text14",
"Id": "45"
},
{
"Selected": true,
"Text": "Text15",
"Id": "87"
},
{
"Selected": true,
"Text": "Text16",
"Id": "80"
}
]
}
]
},
{
"Status": "Met",
"Text": "Text17",
"Id": "KKK",
"ContentItems": [
{
"Text": "Text18",
"Id": "12"
},
{
"Status": "NotMet",
"Text": "Text19",
"Id": "14",
"ContentItems": [
{
"Text": "Text20",
"Id": "55"
},
{
"Selected": true,
"Text": "Text21",
"Id": "98"
}
]
}
]
}
]
}
]
}
]
}
]
};
From the JSON file we need the following:
1.Return true if all "Status" is "Met".
2.Return false if any "Status" is "NotMet".
Since Child nodes can be any level deep; I used recursion function to traverse to each node and from there i'm looping over the child nodes and recursively calling the function.
I tried this code but its not working as expected.
function isStatusMet(response) {
if (response.Status == 'NotMet') {
return false;
} else {
if (response.ContentItems) {
if(Array.isArray(response.ContentItems)) {
for(var i = 0; i < response.ContentItems.length;i++) {
if (response.ContentItems[i].ContentItems) {
return isStatusMet(response.ContentItems[i]);
} else {
if (response.ContentItems[i].Status == 'NotMet') {
return false;
} else {
continue;
}
}
}
return true;
}
}
}
}