首页 > 解决方案 > 如果该对象中的所有值都为 0,如何删除该对象

问题描述

我有一个像这样的对象

const data = {
   "CD": {
      "open": 0,
      "maxItemPrice": 0,
      "totalRevenue": 0
    },
   "DDA 1": {
      "price_category": "DDA 1",
      "items_for_sale": 24,
      "aggregate_holds": null,
      "aggregate_kills": null,
      "held": 35,
      "maxItemPrice": 37.5,
      "totalRevenue": 225,
      "open": 0,
      "sold": 11,
      "sellableCapacity": -11,
      "oversoldCount": 22
    },
   "DDA 2": {
      "price_category": "DDA 2",
      "items_for_sale": 48,
      "aggregate_holds": null,
      "aggregate_kills": null,
      "held": 80,
      "maxItemPrice": 33.33,
      "totalRevenue": 266.6400146484375,
      "sold": 16,
      "sellableCapacity": -32,
      "oversoldCount": 48,
      "open": 0
    },
   "DDA 3": {
      "items_for_sale": 0,
      "aggregate_holds": null,
      "aggregate_kills": null,
      "held": 0,
      "maxItemPrice": 0,
      "totalRevenue": 0,
      "sold": 0,
      "sellableCapacity": 0,
      "oversoldCount": 0,
      "open": 0
    },
}

并且我想删除所有值都是虚假的所有对象,在这种情况下0and null,所以最终结果将是这样的:

const data = {
   "DDA 1": {
      "price_category": "DDA 1",
      "items_for_sale": 24,
      "aggregate_holds": null,
      "aggregate_kills": null,
      "held": 35,
      "maxItemPrice": 37.5,
      "totalRevenue": 225,
      "open": 0,
      "sold": 11,
      "sellableCapacity": -11,
      "oversoldCount": 22
    },
   "DDA 2": {
      "price_category": "DDA 2",
      "items_for_sale": 48,
      "aggregate_holds": null,
      "aggregate_kills": null,
      "held": 80,
      "maxItemPrice": 33.33,
      "totalRevenue": 266.6400146484375,
      "sold": 16,
      "sellableCapacity": -32,
      "oversoldCount": 48,
      "open": 0
    }
};

如果它是虚假的,我知道如何从对象中删除具体值,我是这样做的

let filteredObject = Object.fromEntries(
     Object.entries(data).filter(([_, v]) => {
        return v.open != 0 && v.open != null;
       })
     );

但如果所有值都存在,我不知道如何删除整个对象0null。我怎样才能做到这一点?任何示例将不胜感激。

标签: javascriptobjectecmascript-6

解决方案


我只是对您的代码进行了小修改,以便为嵌套对象的所有属性启用它:

let filteredObject = Object.fromEntries(
     Object.entries(data).filter(([_, v]) => {
        return Object.values( v ).some( (el) => el );
       })
     );

Object.values( v )将返回一个包含嵌套对象中所有值的数组。使用.some()我们可以检查至少一个属性具有真实值。


推荐阅读