Javascript 检查对象的所有值及其嵌套对象

标签 javascript nested-object

您好,我目前遇到这个问题,如果其中的所有值都为 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/

相关文章:

javascript - 在 React JS 中呈现 n 级嵌套对象的最有效方法是什么?

Javascript SQL 请求 Bad Field Error in where 子句

javascript - Node Js - 展平对象数组

javascript ~ 将一个 div 变成一个按钮

javascript - 为什么它显示不同的 “clientWidth” 值只是因为我设置了 “setInterval” 函数?

javascript - ReactJS - 循环遍历子对象并在父对象中显示前 10 个子对象

java - 从 Android Retrofit2 发布嵌套对象,服务器接收子元素 null

javascript - 在javascript中从其他对象递归创建嵌套对象

javascript - 如何在javascript中检测屏幕分辨率

php - 方法: how to change URL without reloading page and index whole URL (with anchor # part)?