【问题标题】:How to remove an object if all values in that object are 0如果该对象中的所有值都为 0,如何删除该对象
【发布时间】:2021-08-03 11:32:00
【问题描述】:

我有一个像这样的对象

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
    },
}

我想删除所有值都是假的所有对象,在本例中为0null,所以最终结果将是这样的:

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,我不知道如何删除整个对象。 我怎样才能做到这一点?任何示例将不胜感激。

【问题讨论】:

    标签: javascript object ecmascript-6


    【解决方案1】:

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

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

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

    【讨论】:

    • 感谢您的回答,这正是我想要的!
    猜你喜欢
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    • 2015-06-03
    • 2020-01-31
    • 2022-07-02
    • 2020-10-12
    • 2021-05-28
    相关资源
    最近更新 更多