Paddy Paddy - 9 days ago 6
AngularJS Question

Check JSON data element value and return "" if Null for a multidimensional non-symmetrical JSON structure

I have an external data source that sometimes returns a value of null, i do not have access to this data source so i cannot change it. My Angular 2 app crashes on a undefined or null value when trying to display the data. I am trying to create a function that catches null or undefined values and sets them to an empty string.

I have found examples for symmetrical JSON structures, but not non-symmetrical nested loop structures

// JSON ARRAY EXAMPLE
[
{
"a":"1",
"x":null,
"y":[
{"k": "3"},
{"i": "5"}
]
},
{
"a":"1",
"x":"2",
"y":[
{"k": "3"},
{"i": "5"},
{"z": "4"},
{"p": null}
]
},
{
"a":null,
"x":"2"
}
]


Current checking function not working

//Checking passes in JSON array
checkData(dataSet) {
dataSet.forEach(function(obj) {
console.log("checking data");
if(!obj || obj === null){
return "";
}
else{
return obj;
}
});
}

qxz qxz
Answer

This is a function that will recursively test/replace every property in a JSON hierarchy:

function process(obj) {
  for (var i in obj) {
    var child = obj[i];
    if (child === null)
      obj[i] = "";
    else if (typeof(child)=="object")
      process(child);
  }
}

// try it out with your sample data
var data = [
 {
  "a":"1",
  "x":null,
  "y":[
       {"k": "3"},
       {"i": "5"}
   ]
 },
 {
  "a":"1",
  "x":"2",
  "y":[
       {"k": "3"},
       {"i": "5"},
       {"z": "4"},
       {"p": null}
   ]
 },
 {
  "a":null,
  "x":"2"
 }
];
process(data);
console.log(data);