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

我只是一个虾纸丫 提交于 2020-07-22 09:45:58

问题


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] = "";
    }
  });
}

回答1:


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": [ "jd@example.com", "jd@example.org" ], "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));
}



回答2:


UPDATE: Since your example objects have keys with value "null" which are Strings and not Objects with value null i updated my answer to correspond your needs.

Try to solve the problem recursive. Everytime the algorithm finds an object in the object the validation routine is called upon this 'new' object.

Here is my fiddle which illustrates a solution: https://jsfiddle.net/vupry9qh/13/

function isNull(obj, key) {
    return (obj[key] == null || obj[key] === undefined || obj[key] === "null");
}

function validate(obj) {
    var objKeys = Object.keys(obj);
  objKeys.forEach((key) => {
    if(isNull(obj, key)) {
        obj[key] = "";
    }
    if(typeof(obj[key]) == "object") {
        validate(obj[key]);
    }
  });
}


来源:https://stackoverflow.com/questions/51513158/check-for-null-replace-it-with-empty-string-for-all-properties-in-a-object-usi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!