---
heading: 'Deep remove falsy'
title: 'Remove all falsy values from an object and its nested children'
date: '2022-09-21'
lastmod: '2024-11-07'
icon: 'Javascript'
draft: false
summary: 'Recursively removes all falsy values (null, undefined, 0, false) from an object and its nested properties.'
tags: [javascript, utils, object]
---

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.

```js:remove-falsy.js showLineNumbers
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

```js:index.js showLineNumbers
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 <Twemoji emoji="clinking-beer-mugs" />
