user3299182
user3299182

Reputation: 601

Return an object key only if value is true

How do i return an object key name only if the value of it is true?

I'm using underscore and the only thing i see is how to return keys which is easy, i want to avoid redundant iterations as much as possible:

example:

Object {1001: true, 1002: false} 

I want an array with only 1001 in it...

Upvotes: 39

Views: 43953

Answers (5)

masyn
masyn

Reputation: 51

In case you will have an object, which has properties different than boolean, you may want to remove them with a filter:

@vsync remixed

const obj = {1001: true, 1002: false, 1003: "foo"};
keys = Object.keys(obj).filter(k => obj[k] === true);

//keys = ["1001"];

Upvotes: 3

Youcef Ali
Youcef Ali

Reputation: 309

obj = {one: false, two: true, three: false, four: true}    
var values = Object.keys(obj).filter(key => obj[key])
console.log(values)

Upvotes: 3

Tom
Tom

Reputation: 26819

There is another alternative, which could be used with Lodash library using two methods:

  • _.pickBy - it creates an object composed of the object properties. If there is no additional parameter (predicate) then all returned properties will have truthy values.
  • _.keys(object) - creates an array of keys from the given object

So in your example it would be:

var obj = {1001: true, 1002: false};
var keys = _.keys(_.pickBy(obj));

// keys variable is ["1001"]

Using Underscore.js library, it would be very similar. You need to use _.pick and _.keys functions. The only difference is that _.pick would need to have predicate function, which is _.identity.

So the code would be as follows:

var obj = {1001: true, 1002: false};
var keys = _.keys(_.pick(obj, _.identity));

// keys variable is ["1001"]

I hope that will help

Upvotes: 17

mu is too short
mu is too short

Reputation: 434645

If you're trying to combine filtering and iterating over an object you're usually after _.reduce (the Swiss Army Knife iterator):

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

Demo: http://jsfiddle.net/ambiguous/2et6T/

Upvotes: 5

adeneo
adeneo

Reputation: 318182

Object.keys gets the keys from the object, then you can filter the keys based on the values

var obj = {1001: true, 1002: false};

var keys = Object.keys(obj);

var filtered = keys.filter(function(key) {
    return obj[key]
});

FIDDLE

Upvotes: 62

Related Questions