Skip to content Skip to sidebar Skip to footer

Is There A Nice Way In Javascript To Removing Falsy Values From A Javascript Object (not An Array)?

In JavaScript you have the nice .filter method to remove null or falsy values from arrays. So far I haven't been able to find a method to remove the same from JavaScript Objects.

Solution 1:

The answer to "can I do x to an object" (or an array for that matter) is usually "yes" and it frequently involves some form of reduce.

If you want to filter falsy values you could do something like this:

function filterFalsy(obj) {
  return Object.keys(obj).reduce((acc, key) => {
    if (obj[key]) {
      acc[key] = obj[key]
    }

    return acc
  }, {})
}

const testObj = {
  a: 'test',
  b: 321,
  c: false
}

console.log(filterFalsy(testObj))

This returns a new object without falsy values and leaves the existing object alone.


Solution 2:

WARNING: There are better answers provided here. Also, thanks to comments made below user's should be warned using delete may provide suboptimal performance.

Filtering invalid values is a little more complex in objects. At face value this will do what you want:

var arr = [ 'apple', 43, false ];
var trueArr = arr.filter(Boolean);

console.log(trueArr);

var obj = { 'title': 'apple', 'id': 43, 'isOrange': false, 'test': 'asd' };
Object.keys(obj)
  .filter(key => !obj[key])
  .forEach(key => delete obj[key]);

console.log(obj);

However, this will not iterate over child objects / functions. This logic also directly modifies the original object (which may or may not be desired).

That can easily changed by adding this logic to a function like so:

function removeFalseyProperties(obj) {
  Object.keys(obj)
    .filter(key => !obj[key])
    .forEach(key => delete obj[key]);
    
  return obj;
}

var testObj = { 'title': 'apple', 'id': 43, 'isOrange': false, 'test': 'asd' };
var trutheyObj = removeFalseyProperties(testObj);

console.log(trutheyObj);

Solution 3:

falsy values are 0, undefined, null, false, etc.

myArray
    .map(item => {
        // ...
    })
    // Get rid of bad values
    .filter(Boolean);

By passing Boolean we can remove all the falsy values.


Post a Comment for "Is There A Nice Way In Javascript To Removing Falsy Values From A Javascript Object (not An Array)?"