Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find key for specific value on object in JS

I have an object as such that has been generated by using the lodash _.zipObject() function. So I have 2 arrays, one of locations, one of numbers.

var locs = {'Aberdeen': 304, 'Aberystwith': 109, 'Belfast': 219, 'Birmingham': 24, 'Brighton': 147, …}

I need to return the key based on an input value. For example, function(304) would return 'Aberdeen'.

I've tried _.findkey(locs, 304); but this just returns undefined. Any other attempt I've tried always returns either undefined or -1. Not really sure where to go from here.

like image 792
Sam Driver Avatar asked Dec 13 '22 20:12

Sam Driver


2 Answers

To find the key use a predicate function with _.findKey():

var locs = {'Aberdeen': 304, 'Aberystwith': 109, 'Belfast': 219, 'Birmingham': 24, 'Brighton': 147 };

var key = _.findKey(locs, function(v) {
  return v === 304;
});

console.log(key);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

You can create the predicate by currying _.eq() with the requested value:

var locs = {'Aberdeen': 304, 'Aberystwith': 109, 'Belfast': 219, 'Birmingham': 24, 'Brighton': 147 };

var key = _.findKey(locs, _.curry(_.eq, 304));

console.log(key);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
like image 144
Ori Drori Avatar answered Dec 28 '22 12:12

Ori Drori


With pure Javascript use Object#keys function to get all keys and then compare with your element in the Array#find function

const obj = {'Aberdeen': 304, 'Aberystwith': 109, 'Belfast': 219, 'Birmingham': 24, 'Brighton': 147};

const key = Object.keys(obj).find(key => obj[key] === 304);

console.log(key);

With lodash pass predicate into the function

const key = _.findkey(locs, (value) => value === 304);
like image 37
Suren Srapyan Avatar answered Dec 28 '22 11:12

Suren Srapyan