Last Updated: May 10, 2016
·
22.81K
· 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: '' } }

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Related Tags
#javascript
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside