Search code examples
javascriptarraysjavascript-objects

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.

Why would this be?

Currently you can create a function for arrays like :

function stripNulls(arr) {
   return arr.filter(Boolean);
}

Is there a similar function that can be created for JS Objects, or is the way filter works not practical on JS Objects.


Solution

  • 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.