Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 273
watsbeat Avatar asked Jan 16 '26 23:01

watsbeat


1 Answers

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);
like image 134
connexo Avatar answered Jan 19 '26 12:01

connexo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!