Leo's dev blog

Remove all falsy values from an object and its nested children

Published on
Published on
/1 mins read/---

This function will remove all falsy values like null, undefined, 0, '', false from an object and its nested children.

Allow passing custom falsyValues to remove and return a new object without the falsy values.

remove-falsy.js
function removeFalsy(obj, falsyValues = ['', null, undefined]) {
  if (!obj || typeof obj !== 'object') {
    return obj
  }
  return Object.entries(obj).reduce((a, c) => {
    let [k, v] = c
    if (falsyValues.indexOf(v) === -1 && JSON.stringify(removeFalsy(v, falsyValues)) !== '{}') {
      a[k] = typeof v === 'object' && !Array.isArray(v) ? removeFalsy(v, falsyValues) : v
    }
    return a
  }, {})
}
Example usage
index.js
let obj = {
  a: 1,
  b: 0,
  c: '',
  d: null,
  e: undefined,
  f: false,
  g: {
    a: 1,
    b: 0,
    c: '',
    d: null,
    e: undefined,
    f: false,
  },
  j: {},
  h: [],
  i: [1],
}
console.log(removeFalsy(obj, [0, false, '', null, undefined]))
// 👉 { a: 1, g: { a: 1 }, i: [ 1 ] }

Happy coding