检查对象中嵌套属性的有效方法是真的吗



基本上有一种简单的方法可以写‘如果这些属性中的任何一个为null,则将整个对象视为null/不返回。’例如,我正在将许多属性映射到一个新对象。

const object = {
one: {a: 'a',
b: 'b',
c: {
c1: 'c1',
c2: null}
},
}
// if properties of object !== null
return {
myObject: {
myA: object.a,
myC1: object.c.c1
myC2: object.c.c2
...
}
}
//else return something else

我宁愿不必写一个巨大的条件来绕过这一点。

使用递归,您可以快速获得一个布尔值,指示对象中是否存在null值。

matchNULLValue每次找到空值属性时都会返回true,嵌套对象也是如此。

const object = {
one: {
a: 'a',
b: 'b',
c: {
c1: 'c1',
c2: null
}
},
}
function matchNULLValue(object) {
for (const value of Object.values(object)) {
if (value === null || (typeof value === "object" && matchNULLValue(value))) {
return true;
}
}
return false;
}
if (matchNULLValue(object)) {
console.log("There is some property on this object with null value.");
} else {
console.log("There is no property on this object with a null value.");
}

function containsNull(obj) {
for (let key in obj) {
if (obj[key] === null) {
return true;
} else if (typeof obj[key] === "object") {
return checkNull(obj[key]);
}
}
return false;
}

您可以使用递归函数来执行该任务。如果任何对象包含null,此函数将返回true。

最新更新