-4

I want to fetch all the keys for a matching value in javascript.

{  
 'aaa': 2,
 'bbb': 7,
 'ccc': 7 
}

I want to fetch all the keys where the value is matching without running a loop.

For example: I am having value 7 and I want to get all the keys which are having value 7 i.e. 'bbb' and 'ccc'. Is there any way to do it?

Andy
  • 61,948
  • 13
  • 68
  • 95
Sweta Sharma
  • 473
  • 2
  • 13

2 Answers2

4

You could get the keys and filter the by checking the value.

var object = { aaa: 2, bbb: 7, ccc: 7 },
    result = Object.keys(object).filter(k => object[k] === 7);

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Something like swap the keys with the values like that ?

var data = {
 'aaa': 2,
 'bbb': 7,
 'ccc': 7 
};

var newData = Object.keys(data).reduce(function(obj,key){
   if (typeof obj[ data[key] ] === 'undefined') {
        obj[ data[key] ] = new Array(key);
   } else {
        obj[ data[key] ].push (key);
   }
   return obj;
},{});
console.log(newData);

Or just for retrieving the keys of matching values like this ?

const keys = Object.keys(data).filter(function(key) {return data[key] === 7});
console.log (keys);
Joël Kwan
  • 21
  • 5