检查是否为空&使用jQuery和JavaScript将其替换为对象中所有属性的空字符串 [英] Check for null & replace it with empty string for all properties in a object using jQuery and JavaScript

查看:113
本文介绍了检查是否为空&使用jQuery和JavaScript将其替换为对象中所有属性的空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON对象,其中包括其他对象和对象列表.必须编写一个函数,该函数迭代对象的所有属性以及对象和对象列表中的对象,并用空字符串替换null.

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

推荐答案

您可以使用JSON.Stringify(请参阅

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));
}

这篇关于检查是否为空&amp;使用jQuery和JavaScript将其替换为对象中所有属性的空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆