Get object keys for filtered values

2020-05-24 20:33发布

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条回答
▲ chillily
2楼-- · 2020-05-24 20:50

This might be easier

result = _.chain(obj)
    .map(function(value, key){
        return value?key:false;
    })
    .filter(function(v){
        return v
    })
    .value();
查看更多
倾城 Initia
3楼-- · 2020-05-24 20:52

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 ;-)

查看更多
放我归山
4楼-- · 2020-05-24 20:54
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" ];
查看更多
家丑人穷心不美
5楼-- · 2020-05-24 20:54

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(":")));
     }
}
查看更多
Fickle 薄情
6楼-- · 2020-05-24 20:58
function findKey(obj, value){
    var key;

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

    return key;
}
查看更多
劫难
7楼-- · 2020-05-24 21:01

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)
查看更多
登录 后发表回答