I am presented with a JSON data structure that contains various keys and values. My goal is to traverse this JSON and extract values for the keys where the 'check' value is set to 'true'.
{
"A_B":{
"ID":"09|_|06",
"address":"ABC",
"name":"2222222222",
"Documents":{
"1":{
"format":"xlsx"
},
"2":{
"format":"pdf"
}
},
"check":true
},
"C_B":{
"ID":"0a|_|0b",
"address":"Los Angeles",
"name":"4444444444",
"Documents":{
"1":{
"format":"docx"
},
"4":{
"format":"xlsx"
}
},
"check":true
},
"C_E":{
"ID":"05|_|06",
"address":"",
"name":"1111111111",
"Documents":{
"5":{
"format":"xlsx"
}
},
"check":false
}
}
Based on the example above, only the values for A_B and C_B should be extracted into a new JSON format. Here is how the new JSON would appear:
{
"A_B":{
"ID":"09|_|06",
"address":"ABC",
"name":"2222222222",
"Documents":{
"1":{
"format":"xlsx"
},
"2":{
"format":"pdf"
}
},
"check":true
},
"C_B":{
"ID":"0a|_|0b",
"address":"Los Angeles",
"name":"4444444444",
"Documents":{
"1":{
"format":"docx"
},
"4":{
"format":"xlsx"
}
},
"check":true
}
}
I have been successful in identifying the IDs [A_B and C_B] where 'check' === true using the following code:
var IDs = Object.keys(completeJson);
var checkTrueIDs = IDs.reduce(function(initArr,ID) {
if(completeJson.check === true) {
initArr.push(ID);
}
return initArr;
},[]);
console.log("IDs wth check === true - " + checkTrueIDs);
However, I am struggling to retrieve the complete object for these identified IDs and incorporate them into a new JSON. When attempting to do so by creating a new JSON object and assigning values inside the conditional statement after the push operation:
var newJson = {}
newJson = completeJson[ID];
The previous values get overwritten, resulting in only retaining one object in the end.