javascript - Remove from JS object where key value is an empty array
问题描述
I'm trying to remove keys from an object where the values is Array(0). Here's the object:
{fruit: Array(1), dairy: Array(2), vegetables: Array(0)}
This is the desired result:
{fruit: Array(1), dairy: Array(2)}
So far, I've been playing with the delete operator and .filter/.reduce methods.
Any help would be awesome :)
解决方案
只需遍历对象的键,检查该键的值是否为空数组,如果是,则将其删除:
let obj = {
a: [1],
b: [],
c: 5,
d: false
}
for (const key in obj) { if (Array.isArray(obj[key]) && !obj[key].length) delete obj[key] };
console.log(obj);
推荐阅读
- c# - C#为DataGridView组合SQL表添加Combobox和Checkbox
- php - laravel 中 boot 和 booted 的区别
- c# - 如何让 File.OpenText 返回不可为空的 StreamReader
- c++ - grpc c++ 的最佳包装器实现是什么?
- elasticsearch - 地理距离 - 弹性搜索
- c++ - 在 C++ Builder 中获取文本文件的第二行
- python-3.x - 使用 pandas 将 Numpy 数组转换为 Dataframe
- amazon-s3 - S3 中 spark.catalog.refreshTable(tablename) 的使用
- entity-framework - 开始使用带有 DB2 的实体框架
- html - 主体和主体之间的 CSS 继承。正文中的 CSS 样式未出现在 html 中