28

The case is simple - I've got a following object:

Object {1: false, 2: true, 3: false, 4: false, 5: false, 6: false, 7: false, 8: true, 12: false, 13: false, 14: false, 15: false, 16: false, 17: false, 18: false, 19: false} 

and I need to get an array of ids that had true value, using underscore. In above case that would be:

[2, 8]

I tried few things but I'm a bit stuck. Does anyone have any idea?

14 Answers 14

43
var keys = [];
_.each( obj, function( val, key ) {
  if ( val ) {
    keys.push(key);
  }
});

There may be easier/shorter ways using plain Underscore.


In case anyone here uses Lodash instead of Underscore, the following is also possible, which is very short and easy to read:

var keys = _.invert(obj, true)[ "true" ];
3
  • 5
    pure javascript (without underscore) is the same long. I was hoping that there's a method that I missed in the docs...
    – ducin
    Commented Jun 7, 2013 at 16:13
  • yeah, probably there isn't any shorter way. Commented Jun 7, 2013 at 17:16
  • There is no method in underscore, but you can easily provide one by using _.extend. Look at my response : you can find first or all keys, and use a function as criteria.
    – gentiane
    Commented Jan 23, 2014 at 21:48
9

Giorgi Kandelaki gave a good answer, but it had some potential problems (see my comment on his answer).

The correct way is:

_(obj).pairs().filter(_.last).map(_.first)

or

_.map(_.filter(_.pairs(obj),_.last),_.first)
1
  • This solution worked for me. The second line of code to be precise. Just replace _.last with the iterator function of your choice and voilà! You have a statement equivalent of yet non-existent underscore method _.findAllKeys. Commented Jun 4, 2015 at 20:29
8
var data = {1: false, 2: true, 3: false, 4: true};

var filteredIds = _.filter(_.keys(data), function (key) {
    return data[key];
});

// result [2, 4]


var rejectedIds = _.reject(_.keys(data), function (key) {
    return data[key];
});

// result [1, 3]
1
  • oh, that's a nice one!
    – ducin
    Commented Jul 15, 2015 at 10:08
6

You can use _.pick. Like this:

var data = {1: false, 2: true, 3: false, 4: false, 5: false, 6: false, 7: false, 8: true, 12: false, 13: false, 14: false, 15: false, 16: false, 17: false, 18: false, 19: false}

var keys = _.keys(_.pick(data, function(value) {
  return value;
}));
1
  • 1
    This solution does not work. Change out data for [{a: true}, {b: false}, {c: true}, {d: false}] and you will get ["0", "1", "2", "3"] Commented Apr 1, 2017 at 3:21
2

You can try this:

_.pairs(obj)
 .filter(function(pair) { return pair[1] })
 .map(function(pair) { return pair[0] })

Or the same but bit more concise:

_.pairs(obj).filter(_.last).map(_.first)
2
  • 2
    There are some problems with your code: both pairs() and filter() return an array, NOT an underscore object, so when calling filter() or map() on that result, you're invoking them on a native array object. That works in modern browsers, but will fail if the browser has no support for Array.filter or Array.map. See my answer for the correct way to do this. Commented Mar 30, 2014 at 23:00
  • Oh, nice finding. Thanks. I just gave a quick answer, not thinking a lot about browser compatibility. Commented Apr 1, 2014 at 8:38
2

You can do it very easily

var obj = { a: false, b: false, c: true, d: false, e: true, f: false };
    name, names;

name = _.findKey(obj, true);
// -> 'c'
names = _.findKeys(obj, true);
// -> ['c', 'e']

For that you juste need to extend underscore a little :

_.mixin({

  findKey: function(obj, search, context) {
    var result,
        isFunction = _.isFunction(search);

    _.any(obj, function (value, key) {
      var match = isFunction ? search.call(context, value, key, obj) : (value === search);
      if (match) {
        result = key;
        return true;
      }
    });

    return result;
  },

  findKeys: function(obj, search, context) {
    var result = [],
        isFunction = _.isFunction(search);

    _.each(obj, function (value, key) {
      var match = isFunction ? search.call(context, value, key, obj) : (value === search);
      if (match) {
        result.push(key);
      }
    });

    return result;
  }
});

And you can even use a function as filter, like this :

var team = {
  place1: { name: 'john', age: 15 },
  place2: { name: 'tim', age: 21 },
  place3: { name: 'jamie', age: 31 },
  place4: { name: 'dave', age: 17 }}

// Determine the places of players who are major
var placeNames = _.findKeys(team, function(value) { return value.age >= 18; });
// -> ['place2', 'place3']

Enjoy ;-)

3
  • 1
    This is incredibly over complicated. Commented Jun 2, 2015 at 23:51
  • What is complicated ? Is it too long to write : name = _.findKey(obj, true);
    – gentiane
    Commented Jun 14, 2015 at 8:13
  • Calling a function is not complicated. Extending underscore to do something that it can already do seems like a complication to me. Commented Jun 16, 2015 at 1:36
2
var obj = {1: false, 2: true /*...*/};

you can use reduce:

_(obj).reduce(function(memo, val, key){
    if (val)
        memo.push(key);
    return memo;
}, []);

or chain map:

_(obj).chain().map(function(val, key){
    if (val)
        return key;
}).reject(_.isUndefined).value();
1

My version:

var list = {
    1: false, 2: true, 3: false, 4: false,
    5: false, 6: false, 7: false, 8: true,
    12: false, 13: false, 14: false, 15: false,
    16: false, 17: false, 18: false, 19: false
};

_.chain(list).map(function(val, key) {
    return val ? parseInt(key) : undefined
}).reject(function(val) {
    return _.isUndefined(val);
}).value();
// returns [2,8]
1

This might be easier

result = _.chain(obj)
    .map(function(value, key){
        return value?key:false;
    })
    .filter(function(v){
        return v
    })
    .value();
0
function findKey(obj, value){
    var key;

    _.each(_.keys(obj), function(k){
      var v = obj[k];
      if (v === value){
        key = k;
      }
    });

    return key;
}
2
  • unfortunately, _.invert(myObject) returns Object {false: "19", true: "8"} so it applies the last matching element. And this is not what I want.
    – ducin
    Commented Jun 7, 2013 at 15:41
  • I am sorry I didn't see your comment earlier. I checked it in jsfiddle, and then realized that. But this should work. Any issues with this version?
    – user1853788
    Commented Jun 7, 2013 at 15:59
0

Another potential solution:

// Your example data
var data = {1: false, 2: true, 3: false, 4: false, 5: false, 6: false, 7: false, 8: true, 12: false, 13: false, 14: false, 15: false, 16: false, 17: false, 18: false, 19: false};

// Outputs the keys: ["2", "8"]
_.keys(_.transform(data, function(r, v, k) { v ? r[k] = 1 : null; }));

// Outputs the keys as integers: [2, 8]
_.map(_.keys(_.transform(data, function(r, v, k) { v ? r[k] = 1 : null; })), _.parseInt)

So basically:

  1. Transform the original object to strip out the false-valued keys
  2. Grab the list of keys from the transformed result
  3. Convert the keys to ints if you need to
1
  • Beware, transform does exist in lodash, but not in underscore.
    – Péha
    Commented Apr 14, 2015 at 9:54
0

I use this one: Retrieve all keys with the same value from an object (not only an object with just boolean values) using lodash

function allKeys(obj, value) {
  _.keys(_.pick(obj, function (v, k) { return v === value; }));
}

Example:

var o = {a: 3, b: 5, c: 3};
var desiredKeys = allKeys(o, 3);
// => [a, c]
0

Heres a way to do it without using any libraries in ES6

let z = {2: true, 3:false, 8:true, 9:false, 10: false}
Array.from(new Set(Object.keys(z).map(function(k){if(z[k]){return k}}))).filter(f=>f)

and out you get [2, 8]

1
  • 1
    alternatively without arrow functions Array.from(new Set(Object.keys(z).map(function(k){if(z[k]){return k}}))).filter(function(f){if(f){return true}})
    – Ricky Sahu
    Commented Apr 3, 2017 at 17:11
-5

I Do not know underscore.js. But using normal JS, I have written the below code.

function myFunction()
{
var str="1: false; 2: true; 3: false; 4: false; 5: false; 6: false; 7: false; 9: true; 12: false";
var n=str.split(";");

for(var i=0;i<n.length;i++)
{
     if(n[i].search("true")!=-1){
     alert(n[i].slice(0,n[i].search(":")));
     }
}
4
  • 1
    this is really NOT what I'm looking for. I've got a plain object, not a string.
    – ducin
    Commented Jun 7, 2013 at 16:12
  • @tkoomzaaskz can't you get the value from the object??
    – TechBytes
    Commented Jun 7, 2013 at 18:38
  • Sorry, I don't understand you. I'm looking for a short underscore solution, just like I wrote in the description.
    – ducin
    Commented Jun 10, 2013 at 10:26
  • Converting a true object to a string representation is like serializing it. One could of course use a JSON serializer for that first and then apply your solution. But, seriously. Why on earth convert the object to string and manipulate that? Working with the true representation is way better, maintenance friendly and sane. The question was also about an underscore solution, which this is not.
    – Spiralis
    Commented Jul 21, 2014 at 2:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.