Javascript - 如果所有属性都为null,则将Object设置为null [英] Javascript - Set Object null if all its properties are null
问题描述
我有一个这样的对象:
var user = {
id: 101,
email: 'jack@dev.com',
personalInfo: {
name: null,
address: {
line1: null,
line2: null,
city: null,
state: null
}
}
}
我想迭代属性并检查它的属性是否为null。如果它们都为null我想将该属性设置为null。这意味着从其全部为null的地址开始,因此设置地址= null,然后名称和地址都为空,因此personalInfo应设置为null等...
I would like to iterate the properties and check if its properties are null. If they are all null I want to set that property null. This means starting from address whose values are all null so set address = null, then name and address are both null so personalInfo should be set null etc...
所以我的对象结束如下:
So my Object ends ups like this:
var user = {
id: 101,
email: 'jack@dev.com',
personalInfo: null
}
推荐答案
您可以迭代所有键/值对并减少此级别的所有 null
值的计数。如果所有值都是 null
,则返回 null
,否则返回更改的对象。
You could iterate all key/value pairs and decrement a count for all null
values for this level. If all values are null
, return null
, otherwise the changed object.
为了检查嵌套对象,取值和类型并再次调用函数并将结果分配给键。
For checking the nested objects, take the value and the type and call the function again and assign the result to the key.
function setNull(object) {
var entries = Object.entries(object),
count = entries.length;
entries.forEach(([k, v]) => {
if (null === (v && typeof v === 'object' && (object[k] = setNull(v)))) {
count--;
}
});
return count
? object
: null;
}
var user = { id: 101, email: 'jack@dev.com', personalInfo: { name: null, address: { line1: null, line2: null, city: null, state: null } } };
console.log(setNull(user));
这篇关于Javascript - 如果所有属性都为null,则将Object设置为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!