kayasa kayasa - 2 months ago 11
AngularJS Question

Angular - append values to a json

I have the following json. I want to traverse this and get values for those keys where 'check' value is '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
}
}


In the example json above, values for A_B and C_B should be added to the new json. The new json would look like

{
"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 am able to get those IDs [A_B and C_B] where 'check' === true, using the below 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 not able to get complete object for these IDs and add them to a new JSON. If I do

var newJson = {}


and then inside the if condition (below the push)

newJson = completeJson[ID];


this overwrites the previous values, so in the end I am left with only one object.

Answer

You can iterate over the object that you have and if its key check is true then add it to the newJson object.

var newJson ={};
    angular.forEach(completeJson, function(value, key) {
    if(value.check){
    newJson[key] = value;
    }
   });
console.log(newJson);