Filtering / Removing all False-y values from an Object

Big Fat Software
2 min readApr 24, 2021

The snippet below definnes an Object in JavaScript. As it can be seen here, the Object has only two properties which aren’t falsy viz. a and b. And we want to filter out all the falsy values and we must retrieve the keys where the value against the key isn't negative.

x = {
a: "foo",
b: `bar`,
c: '',
d: null,
e: undefined,
f: 0,
g: false
};
Object.keys(x).filter((key) => x[key]);

The task can be modified a little bit by asking for the values instead of the keys, or asking for both the key and the values instead of just the key. More-or-less, the idea behind the snippet will remain same.

The snippet below extracts the values instead of the keys. One little addition of a map function does it. I have a faith that it can be further optimized. But I can live with this one too.

Object.keys(x).filter((key) => x[key]).map((key) => x[key]);

Originally published at http://bigfatsoftwareinc.wordpress.com on April 24, 2021.

--

--