ash*_*pal 1 javascript jquery promise deferred
我有一个 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] = "";
}
});
}
Run Code Online (Sandbox Code Playgroud)
您可以使用JSON.Stringify(参见MDN)和替换方法来替换nulls 中的所有s 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));
}Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8010 次 |
| 最近记录: |