我有一个JSON对象,其中包括其他对象和对象列表。必须编写一个函数,该函数遍历对象的所有属性以及对象和对象列表中的对象,并用空字符串替换null
。
由于它是循环内循环,因此我需要实现延迟的顺序处理。我尝试了很多方法,但是失败了。任何人都可以帮忙。
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] = "";
}
});
}
答案 0 :(得分:1)
您可以将JSON.Stringify
(请参阅MDN)与替换方法一起使用,以替换null
中的所有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));
}
答案 1 :(得分:0)
更新:由于您的示例对象具有值为“ null”的键(它们是字符串)而不是值为null的对象,因此我更新了答案以符合您的需求。
尝试递归解决问题。每当算法在对象中找到对象时,都会在此“新”对象上调用验证例程。
这是我的小提琴,它说明了一种解决方案: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]);
}
});
}