首页 > 解决方案 > 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 :)

标签: javascriptarraysobject

解决方案


只需遍历对象的键,检查该键的值是否为空数组,如果是,则将其删除:

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);


推荐阅读