我有一个这样的对象:
var user = {
id: 101,
email: 'jack@dev.com',
personalInfo: {
name: null,
address: {
line1: null,
line2: null,
city: null,
state: null
}
}
}
我想迭代属性并检查其属性是否为null。如果它们全为空,我想将该属性设置为空。这意味着从值全部为null的地址开始,因此将address设置为null,然后name和address都为null,因此personalInfo应该设置为null等等。
所以我的对象像这样结束:
var user = {
id: 101,
email: 'jack@dev.com',
personalInfo: null
}
答案 0 :(得分:0)
您可以像这样递归执行此操作:
function isAllNull(obj) { // this function checks if an object contain only null values, i.e. checks if it is a null object or not
for(var key in obj) {
if(obj[key] !== null) { // if there is at least one property that is not null
return false; // then the object doesn't qualify
}
}
return true; // otherwise if all properties are null
}
function nullify(obj) { // this function takes an object and replace all its null child objects with null
for(var key in obj) {
if(obj[key] && typeof obj[key] === "object") { // if the current value is an object
nullify(obj[key]); // nullfiy it first (turn its null children objects to null)
if(isAllNull(obj[key])) { // then check if it is a null object
obj[key] = null; // if so replace it with null
}
}
}
}
示例:
function isAllNull(obj) {
for(var key in obj) {
if(obj[key] !== null) {
return false;
}
}
return true;
}
function nullify(obj) {
for(var key in obj) {
if(obj[key] && typeof obj[key] === "object") {
nullify(obj[key]);
if(isAllNull(obj[key])) {
obj[key] = null;
}
}
}
}
var user = {
id: 101,
email: 'jack@dev.com',
personalInfo: {
name: null,
address: {
line1: null,
line2: null,
city: null,
state: null
}
}
};
nullify(user);
console.log(user);
答案 1 :(得分:0)
您可以迭代所有键/值对并减少此级别的所有null
值的计数。如果所有值均为null
,则返回null
,否则返回已更改的对象。
要检查嵌套对象,请获取值和类型,然后再次调用该函数并将结果分配给键。
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));
答案 2 :(得分:0)
通过传递一个对象来调用此函数,它将根据需要返回对象,
function setNulls(obj) {
var flag = false;
for (var key in obj) {
if (obj[key] != null && typeof obj[key] == "object") {
obj[key] = setNulls(obj[key]);
}
if (obj[key] != null) {
flag = true;
}
}
if (flag)
return obj;
else
return null;
}