Javascript - removing undefined fields from an object

Damian picture Damian · Aug 21, 2014 · Viewed 106.3k times · Source

Is there a clean way to remove undefined fields from an object?

i.e.

> var obj = { a: 1, b: undefined, c: 3 }
> removeUndefined(obj)
{ a: 1, c: 3 }

I came across two solutions:

_.each(query, function removeUndefined(value, key) {
  if (_.isUndefined(value)) {
    delete query[key];
  }
});

or:

_.omit(obj, _.filter(_.keys(obj), function(key) { return _.isUndefined(obj[key]) }))

Answer

Rotareti picture Rotareti · Jul 13, 2016

A one-liner using ES6 arrow function and ternary operator:

Object.keys(obj).forEach(key => obj[key] === undefined ? delete obj[key] : {});

Or use short-circuit evaluation instead of ternary: (@Matt Langlois, thanks for the info!)

Object.keys(obj).forEach(key => obj[key] === undefined && delete obj[key])

jsbin

Same example using if expression:

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

If you want to remove the items from nested objects as well, you can use a recursive function:

const removeEmpty = (obj) => {
  Object.keys(obj).forEach(key => {
    if (obj[key] && typeof obj[key] === 'object') removeEmpty(obj[key]);
    else if (obj[key] === undefined) delete obj[key];
  });
  return obj;
};

jsbin