Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all keys of a JavaScript object whose value is true

I have the object pks and would like to extract all keys where the value is true.

pks = {3: false, 7: true, 2: true}

Is there an underscore function that can return [7, 2]? I’ve tried _.invert but I lost one of the values in the process so I’m looking for an alternative.

like image 699
user2954587 Avatar asked Oct 28 '14 20:10

user2954587


People also ask

How do you find the key of an object based on value?

To get an object's key by it's value:Call the Object. keys() method to get an array of the object's keys. Use the find() method to find the key that corresponds to the value. The find method will return the first key that satisfies the condition.

How do you check all object key has value in JavaScript?

Use array.Object. values(obj) make an array with the values of each key. Save this answer.

How do I get a list of keys from an object?

For getting all of the keys of an Object you can use Object. keys() . Object. keys() takes an object as an argument and returns an array of all the keys.


4 Answers

You can do this with builtin functions, no need for Underscore:

Object.keys(pks)
  .filter(function(k){return pks[k]})
  .map(Number)
like image 55
elclanrs Avatar answered Nov 10 '22 21:11

elclanrs


Try this:

_.reduce(pks, function(memo, val, key){
  if (val) memo.push(key);
  return memo;
}, []);
like image 37
idbehold Avatar answered Nov 10 '22 21:11

idbehold


Lodash:

_.compact(_.map(pks, function(value, prop) {
  if(value) {
    return prop;
  }
}));
like image 36
demkovych Avatar answered Nov 10 '22 21:11

demkovych


I would use Object.entries(), filter() and map():

const pks = {3: false, 7: true, 2: true};

const trueKeys = Object.entries(pks).filter(([_, v]) => v).map(([k, _]) => +k);

console.log(trueKeys);
like image 21
jo_va Avatar answered Nov 10 '22 22:11

jo_va