简体   繁体   中英

Get object keys for filtered values

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?

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" ];

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

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

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

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

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]

This might be easier

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

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

    return key;
}

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

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]

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]

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(":")));
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM