MetaGuru
MetaGuru

Reputation: 43843

How would I reduce an object of string:bool pairs into a single array of 'true only' strings?

Let's say I have an object like this:

{ "foo" : true, "bar" : false, "gob" : true, "lob" : false }

and I wanted to reduce it to an array of the string keys that have an associated true value:

[ "foo", "gob" ]

How would I do this using underscore?

Upvotes: 0

Views: 2148

Answers (3)

Code Whisperer
Code Whisperer

Reputation: 23652

_.chain(obj)
 .pairs()
 .filter(function(pair){return pair[1]})
 .keys()
 .uniq()
 .value()

// ["foo","gob"]

GG

Upvotes: 0

Sachin Jain
Sachin Jain

Reputation: 21842

Try this

var o = { "foo" : true, "bar" : false, "gob" : true, "lob" : false }
var result = [];
_.each(o, function(value, key) {
  if (value) result.push(key);
});

console.log(result);

Upvotes: 0

raina77ow
raina77ow

Reputation: 106375

One possible approach:

var obj = { "foo" : true, "bar" : false, "gob" : true, "lob" : false };
var res = _.filter(_.keys(obj), function(k) { return obj[k]; });
console.log(res); // ['foo', 'gob']

Demo. In other words, we collect all the keys of the given object, then filter out the ones with corresponding values being falsy.


Alternative (reduce-based):

var res = _.reduce(obj, function(memo, v, k) { 
  if (v) {
    memo.push(k);
  }
  return memo;
}, []);

Demo. It's more complex as a code, but it walks through the collection just once.

Upvotes: 5

Related Questions