您好,我目前遇到这个问题,如果其中的所有值都为 null 或 0,则检查具有另一个嵌套对象的对象
我的目标如下:
{
"city":0,
"road":{
"max":null,
"min":null
},
"size":{
"max":null,
"min":null
},
"type":null,
"ward":0,
"floor":null,
"price":{
"max":null,
"min":null
},
"street":0,
"toilet":null,
"balcony":null,
"bedroom":null,
"district":0,
"frontend":{
"max":null,
"min":null
},
"direction":null,
"living_room":null
}
我需要检查其中的每个值是 0 还是 null,如果所有值都是 0 或 null,则返回 true,如果任何值不同于空或 0
我不能使用:
Object.values(object).every(i => (i === null || i === ''))
它返回 False,因为嵌套对象仍然被视为与 0 和 null 不同的值
如果条件一次检查它的每个值,我不想写超长
是否有遍历对象及其嵌套对象来检查?
最佳答案
您可以采用迭代和递归方法。
function check(object) {
return Object.values(object).every(v => v && typeof v === 'object'
? check(v)
: v === 0 || v === null
);
}
var data0 = { city: 0, road: { max: null, min: null }, size: { max: null, min: null }, type: "sell", ward: 0, floor: null, price: { max: null, min: null }, street: 0, toilet: null, balcony: null, bedroom: null, district: 0, frontend: { max: null, min: null }, direction: null, living_room: null },
data1 = { city: 0, road: { max: null, min: null }, size: { max: null, min: null }, type: null, ward: 0, floor: null, price: { max: null, min: null }, street: 0, toilet: null, balcony: null, bedroom: null, district: 0, frontend: { max: null, min: null }, direction: null, living_room: null };
console.log(check(data0)); // false because of type: "sell"
console.log(check(data1)); // true
关于Javascript 检查对象的所有值及其嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58554096/