JS Remove empty keys from an object

Viewed 1178
const obj = {
  a: '123',
  b: '124',
  c: '1242414',
  d: '',
  e: '',
  f: ''
}

What's the right way to remove keys with empty values from an object?

Here's what I've tried, but can't finalize it..

Object.entries(obj).filter(item => item !== "");
4 Answers

Using filter as you did, returns an Array instead of an Object.
reduce is better, since it can return any type you wish.


ES2015

const obj = {
  a: '123',
  b: '124',
  c: '1242414',
  d: '',
  e: '',
  f: ''
}

// creates a new object, without empty keys
console.log(
  Object.entries(obj).reduce((acc, [k, v]) => v ? {...acc, [k]:v} : acc , {})
)

// or mutate the original object
console.log(
  Object.keys(obj).reduce((acc, k) => (!obj[k] && delete acc[k],  acc), obj),
  obj // print original to prove it was mutated
)

Or another simple mutation:

Object.keys(obj).forEach(k => !obj[k] && delete obj[k])

Classic javascript: (most efficient)

const obj = {
  a: '123',
  b: '124',
  c: '1242414',
  d: '',
  e: '',
  f: ''
}

for(let k in obj)
  if( obj[k] == '' )
    delete obj[k]

console.log(obj)

You can write it as one-liner if you want it shorter :p

for(let k in obj) obj[k] == '' && delete obj[k]

If you know keys will never have 0 as values, you can do:

for(let k in obj) !obj[k] && delete obj[k]

The item in your callback is an array containing the key and the value. So, return whether the second item in the array is something other than '', and turn it back into an object with `Object.fromEntries:

const obj = {
  a: '123',
  b: '124',
  c: '1242414',
  d: '',
  e: '',
  f: ''
};
console.log(
  Object.fromEntries(
    Object.entries(obj)
      .filter(item => item[1] !== "")
  )
);

The below code step by step tells how to achieve this.

const obj = {
  a: '123',
  b: '124',
  c: '1242414',
  d: '',
  e: '',
  f: ''
}

const o = Object.entries(obj);
console.log(o);

const f = o.filter(keyValues=>{
 return  keyValues[1]!==""
});

console.log(f);

const filtered = Object.fromEntries(f);

console.log(filtered)

Here is one using forEach. I do think using delete is most prudent when it comes to deleting object elements:

const obj = {
  a: '123',
  b: '124',
  c: '1242414',
  d: '',
  e: '',
  f: ''
};

Object.keys(obj).forEach(key => {
  if(!obj[key])
    delete obj[key]
});

console.log(obj)

Related