javascript - 如果该对象中的所有值都为 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
},
}
并且我想删除所有值都是虚假的所有对象,在这种情况下0
and 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;
})
);
但如果所有值都存在,我不知道如何删除整个对象0
或null
。我怎样才能做到这一点?任何示例将不胜感激。
解决方案
我只是对您的代码进行了小修改,以便为嵌套对象的所有属性启用它:
let filteredObject = Object.fromEntries(
Object.entries(data).filter(([_, v]) => {
return Object.values( v ).some( (el) => el );
})
);
Object.values( v )
将返回一个包含嵌套对象中所有值的数组。使用.some()
我们可以检查至少一个属性具有真实值。
推荐阅读
- node.js - 从 Crontab 运行时,Puppeteer “TimeoutError: Navigation Timeout Exceeded: 30000ms exceeded”
- azure - 删除嵌套日期文件夹 getdate() < 5 date
- python - 从字典列表值中获取值
- docker - 如何在 jenkins 中构建 dotnetcore 项目?
- javascript - 尝试登录时代码返回 net::ERR_EMPTY_RESPONSE。当 true 应该打开 LoggedIn.html 页面
- java - Pentaho 用户控制台缺少用于修改的 Java 脚本值的“MultipartEntityBuilder”
- r - 允许 MLE 中的估计参数因国家/地区而异
- python - 使用python消除两个文本块之间的重叠
- reactjs - 来自自定义钩子的 Useeffect 依赖列表警告
- java - 为什么我得到这个空引用对象?