0

I have an object that contains only simple key value pairs and I want to filter out any properties have falsey values. Is this possible using Array.prototype.filter()?

qbolt
  • 543
  • 3
  • 10
  • 17
  • 1
    Please read [ask]. Key phrases: "Search, and research" and "Explain ... any difficulties that have prevented you from solving it yourself". – Heretic Monkey Feb 20 '17 at 22:15

1 Answers1

2

Is this possible using Array.prototype.filter()?

Yes, but not directly: You can do it after using Object.keys or similar:

var arrayOfTruthyValues = Object.keys(obj).filter(key => obj[key]);

The result is an array of truthy values.

If you want the end result to be an object, combining filter with reduce could do it:

var newObj = Object.keys(obj)
    .filter(key => obj[key])
    .reduce((newObj, key) => {
        newObj[key] = obj[key];
        return newObj;
     }, {});

That's mostly just using reduce as a looping construct (since we never actually change the accumulator value, we just keep returning the same object) which is sometimes considered an "abusage." :-) And it means we could do without the filter part and just put an if in the reduce, but...


Note that Object.keys only includes an object's own, enumerable properties. If you want own properties even if they're not enumerable, that would probably be Object.getOwnPropertyNames instead.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • We had a small argue and I'm looking forward for your opinion in this case. Who got the right? Who's answer is totally wrong? If you could say something... http://stackoverflow.com/questions/42356481/how-to-get-the-last-key-of-object-which-has-a-value/42356557 – kind user Feb 21 '17 at 01:04