Search code examples
javascriptjquerypromisedeferred

Check for null & replace it with empty string for all properties in a object using jQuery and JavaScript


I have a JSON object, which includes other objects and list of objects. Have to write a function, which iterates through all properties of objects as well as object within object and list of objects and replace null with an empty string.

As it is loop inside loop, I need to implement deferred so sequential processing. I tried many ways, but failed. Anyone please help.

function ValidateObject(result) {
  var aObj = result.A;
  aObj = VerifyForNull(aoBJ);
  var bObj = result.B;
  bObj = VerifyForNull(bObJ);
  for (var i = 0; i < result.C.length; i++) {
    var cObj = result.C[i];
    cObj = VerifyForNull(cObJ);
    for (var j = 0; j < cObj.D.length; j++) {
      var dObj = cObj.D[i];
      dObj = VerifyForNull(dObj);
    }
  }
}

function VerifyForNull(obj) {
  Object.keys(obj).forEach(function(key) {
    var val = obj[key];
    if (val == null || value === undefined) {
      obj[key] = "";
    }
  });
}

Solution

  • You can use JSON.Stringify (see MDN) with a replacer method to replace all nulls in an Object:

    console.log(replaceNull({
        x: {},
        y: null,
        z: [1,null,3,4],
        foo: "foo",
        bar: {foobar: null}
      }));
    
    const yourObj = { "person": { "id": 12345, "name": "John Doe", "phones": { "home": "800-123-4567", "mobile": null }, "email": [ "[email protected]", "[email protected]" ], "dateOfBirth": null, "registered": true, "emergencyContacts": [ { "name": "Jane Doe", "phone": null, "relationship": "spouse" }, { "name": "Justin Doe", "phone": "877-123-1212", "relationship": undefined } ] } };
    
    console.log(replaceNull(yourObj, ""));
    
    function replaceNull(someObj, replaceValue = "***") {
      const replacer = (key, value) => 
        String(value) === "null" || String(value) === "undefined" ? replaceValue : value;
      //^ because you seem to want to replace (strings) "null" or "undefined" too
      
      return JSON.parse( JSON.stringify(someObj, replacer));
    }