Last Updated: May 10, 2016
·
22.52K
· harrygogonis

Remove Falsy values (or empty strings) from JavaScript objects

Description

This method iterates over an object and removes all keys with falsy values.
That is, falsy values will cause the key/value pair to be removed from the object. This is very useful for removing unwanted data from an object.

See this page for more information about falsy values.

Note this does a "shallow" pass, so nested falsy values will not be removed.

Code

// ES6 Syntax
const removeFalsy = (obj) => {
  let newObj = {};
  Object.keys(obj).forEach((prop) => {
    if (obj[prop]) { newObj[prop] = obj[prop]; }
  });
  return newObj;
};

// Old syntax
var removeFalsy = function removeFalsy(obj) {
  var newObj = {};
  Object.keys(obj).forEach(function (prop) {
    if (obj[prop]) {
      newObj[prop] = obj[prop];
    }
  });
  return newObj;
};

Example

var obj = {
    key1: 0,
    key2: "",
    key3: false,
    key4: "hello!",
    key7: { key8: "" }, // nested value won't be removed
};

console.log(removeFalsy(obj)) // { key4: 'hello!', key7: { key8: '' } }

Modifications

If you only want to check for empty strings or something similar,
it is easy to modify the code.

const removeEmptyStrings = (obj) => {
  let newObj = {};
  Object.keys(obj).forEach((prop) => {
    if (obj[prop] !== '') { newObj[prop] = obj[prop]; }
  });
  return newObj;
};

...

console.log(removeEmptyStrings(obj))
// { key1: 0, key3: false, key4: 'hello!', key7: { key8: '' } }