Remove from JS object where key value is an empty array

青春壹個敷衍的年華 提交于 2021-02-10 03:07:25

问题


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


回答1:


Just iterate over the keys of the object, check if the value for that key is an empty array and if so, delete it:

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



回答2:


The filter/reduce operators are for Arrays not for objects. If you must use the filter/reduce operators, you can try:

const obj = {a: [1], b: [1,2], c: []};

const filtered = Object.keys(obj)
  .filter(key => Array.isArray(obj[key]) && obj[key].length != 0)
  .reduce((acc, key) => {acc[key] = obj[key]; return acc}, {});
  
console.log(filtered);


来源:https://stackoverflow.com/questions/56284246/remove-from-js-object-where-key-value-is-an-empty-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!