I have a quite simple JavaScript object, which I use as an associative array. Is there a simple function allowing me to get the key for a value, or do I have to iterate the object and find it out manually?
-
There is no such standard function to do this. If the mapping is truly bidirectional then it is trivial to construct a "flipped" map and index that. Otherwise a simple property-iterator (with a hasOwnProperty gaurd, perhaps) and an early-return hidden inside a function does just nicely... – Mar 28 '12 at 12:27
-
How could this work if an object was referenced by more than one key? `var o = []; var map = {first: o, second: o}`. What would `find_key(o)` return? – Gareth Mar 28 '12 at 12:49
-
5doesn't matter ;) I only intended to use it for an array with unique key-value-pairs. – arik Mar 30 '12 at 20:31
-
Possible duplicate of [best way to get the key of a key/value javascript object](http://stackoverflow.com/questions/6268679/best-way-to-get-the-key-of-a-key-value-javascript-object) – Andy Feb 04 '16 at 18:02
-
1I've made a version without iteration https://stackoverflow.com/a/36705765/696535. It would be interesting to test all proposed solutions in jsfiddle – Pawel Feb 01 '18 at 22:04
31 Answers
function getKeyByValue(object, value) {
return Object.keys(object).find(key => object[key] === value);
}
ES6, no prototype mutations or external libraries.
Example,
function getKeyByValue(object, value) {
return Object.keys(object).find(key => object[key] === value);
}
const map = {"first" : "1", "second" : "2"};
console.log(getKeyByValue(map,"2"));

- 890
- 8
- 17

- 11,903
- 2
- 16
- 11
-
12Well, really clean if you don't support IE11 :-)If so, you need a polyfill – Chexpir Mar 02 '17 at 10:23
-
4Depending on the implementation, this probably takes *O(n)* space since `keys()` materializes the key set. – David Ehrmann Oct 19 '17 at 01:04
-
2
-
13If Multiple keys have Same value use filter instead of find `function getKeyByValue(object, value) { return Object.keys(object).filter(key => object[key] === value); }` – saketh May 28 '19 at 14:22
-
6Lol. This is not slow, it’s O(n) which is pretty much the best possible runtime. – Ben Wainwright Jan 10 '20 at 18:36
-
1@BenWainwright: Θ(n) is the pretty much the worst runtime for this problem without actively trying to make a slow implementation. – Ry- Feb 27 '20 at 00:55
-
1@Ry- so beat it. What’s the solution in better than n? Literally every other solution I’ve seen on this page has been at *least* o(n) – Ben Wainwright Feb 27 '20 at 01:29
-
3@BenWainwright: Maintaining a `BiMap` or equivalent (Alethes’s answer) is often the efficient O(1) approach to the broader problem, but even for one-offs it’s at least possible to iterate with `for in` and break upon finding a match, rather than creating an entire array of keys ahead of time, leading to a best case better than the worst case. That is, O(position) instead of O(size). (The only answer on this page worse than O(size) is the silly JSON one.) – Ry- Feb 27 '20 at 02:33
-
2@Ry- Alethes answer is not a valid answer to the question as asked ... yeah sure there are plenty of things you can do if you change the preconditions but the asker asked how to find a value out of a plain object. – Ben Wainwright Feb 27 '20 at 02:41
-
1My comment referred to worst case runtime (you know... big O). An early exit from a loop is irrelevant. – Ben Wainwright Feb 27 '20 at 02:42
-
1
-
this fails when its consequitive values ex - const map = {"first" : "2", "second" : "2"}; console.log(getKeyByValue(map,"2")); – jaibalaji Apr 25 '20 at 12:19
-
1
-
No standard method available. You need to iterate and you can create a simple helper:
Object.prototype.getKeyByValue = function( value ) {
for( var prop in this ) {
if( this.hasOwnProperty( prop ) ) {
if( this[ prop ] === value )
return prop;
}
}
}
var test = {
key1: 42,
key2: 'foo'
};
test.getKeyByValue( 42 ); // returns 'key1'
One word of caution: Even if the above works, its generally a bad idea to extend any host or native object's .prototype
. I did it here because it fits the issue very well. Anyway, you should probably use this function outside the .prototype
and pass the object into it instead.

- 231,737
- 57
- 305
- 359
-
2Actually it's ok if you know things like that the for-in loop goes down the property chain which means "for(var key in obj)" would give you "getKeyByValue" as "key" at some point. – Oct 22 '12 at 15:16
-
Oh man I love how this stealthfully returns undefined if the value doesn't exist. Well done. Also, just a point of interest, this would perform O(n) so if the object had a ton of properties (like a list of people in a big city and their addresses), you'd probably want a more efficient search. Maybe sort values and binary search? Eh? – corbin Nov 10 '13 at 17:02
-
Thanks a lot, by the time I saw bad idea, I wonder why then I searched through this and added here for this answer enhancement and extensive reading. http://stackoverflow.com/questions/3085240/prototyping-javascript-native-types-discouraged – 西門 正 Code Guy May 16 '14 at 02:40
-
2@jAndy it is NOT ===, it is ==. Your code does not work with ===. It returns undefined. – Dexter Jan 06 '15 at 19:44
-
I think Converting it to a string would be better to fix type errors just add `.toString()` like `obj[ key ].toString()` and to the value if desired... – CrandellWS Jan 06 '15 at 20:19
-
Definitely follow the word of caution and pass the object into a standard function instead. This can save you some trouble :) – markj Jun 10 '15 at 15:51
-
This mutates the prototype of Object, which is a horrible approach to doing this. See: https://stackoverflow.com/questions/23807805/why-is-mutating-the-prototype-of-an-object-bad-for-performance – Jon Koops Jan 06 '16 at 17:47
-
@JonKoops: You’re right that adding to `Object.prototype` is bad, but that question link is about changing the prototype of *an* object. – Ry- Feb 27 '20 at 00:58
As said, iteration is needed. For instance, in modern browser you could have:
var key = Object.keys(obj).filter(function(key) {return obj[key] === value})[0];
Where value
contains the value you're looking for.
Said that, I would probably use a loop.
Otherwise you could use a proper "hashmap" object - there are several implementation in JS around - or implement by your own.
UPDATE 2018
Six years passed, but I still get some vote here, so I feel like a more modern solution – for modern browser/environment – should be mentioned in the answer itself and not just in the comments:
const key = Object.keys(obj).find(key => obj[key] === value);
Of course it can be also a function:
const getKeyByValue = (obj, value) =>
Object.keys(obj).find(key => obj[key] === value);

- 24,846
- 5
- 51
- 54
-
22
-
Unfortunately the arrow function is not any "modern" browser yet, so it's a bit useless at the moment – I'm using it in jetpack on Firefox Nightly, it will be in Firefox 22. Anyway, I'm not aware about any `or` array's method, and it's not clear to me its purpose here: I will appreciate some additional detail! :) – ZER0 Jun 23 '13 at 18:40
-
1As for arrow, it's coming and I'm waiting for it :) As for `or` sure! It was only recently evaluated and accepted (I don't think anyone implements it yet). What it does is find the first element of an array matching a predicate and return it. So `[1,2,3,4].or(x=>x>2)` would return `3` and `[1,2,3,4,5].or(x=>x<3)` would return `1`. Something like C#'s FirstOrDefault :) – Benjamin Gruenbaum Jun 23 '13 at 18:43
-
Yeah, arrow is coming but it will takes to be used widely – unless as I do, someone's working on a specific engine. I wasn't aware of new proposal for ES6, I thought was pretty closed: do you have a link about the `or` method? From what you mentioned it seems that it returns the item that match the predicate "or" the array itself? – ZER0 Jun 24 '13 at 06:56
-
Looks like it was renamed to `Array.prototype.find` and `Array.prototype.findIndex` (for finding the index rather than the element :) https://github.com/Ralt/or/issues/1#issuecomment-14940411 – Benjamin Gruenbaum Jun 24 '13 at 07:16
-
Isn't this very inefficient for objects with lots of keys? `filter` will traverse the entire set of keys first, and then the first element is taken. It would be more efficient to bail out after finding the first (if any) match. – Frerich Raabe Jan 13 '16 at 14:53
-
@BenjaminGruenbaum `Object.keys(movementArr).or(o => console.log('OP', o));` I'm getting error with your code. Help me please? – sg552 Jan 31 '18 at 03:39
-
3@sg552 as it was mentioned later, `or` was renamed. I believe now you should use [find](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find). – ZER0 Feb 01 '18 at 15:27
-
`entries` or `keys` are "iteration", just not explicit one – my original comment doesn't use `for` loop but I consider this iteration anyway. The link you posted doesn't add anything more than what was said in this thread, honestly. – ZER0 Feb 02 '18 at 09:15
-
-
You mean something like: `const data = {"foo": 10, "bar": 20}; console.log(getKeyByValue(data, 20))`? I can update the answer if that was what you asked! – ZER0 Feb 14 '19 at 17:00
Shortest One Liners
let key = Object.keys(obj).find(k=>obj[k]===value);
Return all keys with the value:
let keys = Object.keys(obj).filter(k=>obj[k]===value);
If value is an Array
or Object
:
let keys = Object.keys(obj).filter(k=>JSON.stringify(obj[k])===JSON.stringify(value));

- 19,976
- 6
- 58
- 55
With the Underscore.js library:
var hash = {
foo: 1,
bar: 2
};
(_.invert(hash))[1]; // => 'foo'
-
442@GeorgeJempty Not everyone wants to load a 5kb library for a simple key lookup ;) – tckmn Jan 12 '14 at 02:45
-
5Just FYI for anyone looking for a solution that will get you ALL keys that match a value: this will not work. – Brett Mar 20 '14 at 06:45
-
2underscore keys will work too. http://underscorejs.org/#keys _.keys({one: 1, two: 2, three: 3}); => ["one", "two", "three"] – Thaddeus Albers May 15 '14 at 19:54
-
1_.invert doesn't work where the values include objects as the default string serialization collides. You might use this abomination: `_.chain(hash).pairs().findWhere({1: 1}).value()[0] ` – DanHorner Feb 09 '15 at 04:48
-
1**A word of caution:** According to the [documentation](http://underscorejs.org/#invert): "For this to work, all of your object's values should be unique and string serializable." – bpromas Oct 17 '16 at 14:01
-
4This should not be the accepted answer, it propose a solution via a library that force a change in the current code structure – Matteo Jan 03 '18 at 11:35
-
@Doorknob problems with 5kb could be solved with `npm i lodash/invert` – Andrew Bazhin Apr 24 '20 at 12:03
The lodash way https://lodash.com/docs#findKey
var users = {
'barney': { 'age': 36, 'active': true },
'fred': { 'age': 40, 'active': false },
'pebbles': { 'age': 1, 'active': true }
};
_.findKey(users, { 'age': 1, 'active': true });
// → 'pebbles'

- 553
- 4
- 2
-
1Lodash is clearly the best solution for this issue. Better even, I find, than the underscore way. – arik Mar 20 '16 at 01:11
-
4FYI, "the underscore way": `_.findKey(users, { 'age': 1, 'active': true });` ...it's the same – craigmichaelmartin Jul 19 '16 at 12:18
-
if array is the value you need to use:- let obj = { a: [1, 2], b: [3, 4], c: [5, 6] } _.findKey(obj, function(val) { return _.isEqual(val, [5, 6]); }); – ashishyadaveee11 Nov 16 '16 at 08:46
-
12if your values are simple, like strings or integers, then contrary to expectation this will not work. e.g. `_.find_key({a: "A", b:"B"}, "B"})` returns`undefined` so as stated [here](https://github.com/lodash/lodash/issues/528) you need to do `_.find_key({a: "A", b:"B"}, _.partial(_.isEqual,"B")})` – ryan2johnson9 Jan 09 '17 at 04:17
-
1@ryan2johnson9 That's my problem with Lodash. I'm having a hard time understanding some functions (apparently I'm the only one). But thanks anyway, it works. I found another, shorter solution. It causes overheap on bigger objects so be careful with this one. `_.invert(haystack)[needle]` – Empi Apr 03 '17 at 15:33
-
@arik: Considering the traffic this question gets, please consider updating which answer is accepted. – Cerbrus Dec 13 '17 at 15:24
-
1To extend the comment by @ryan2johnson9, when the values are primitives (string, integers, ...) you need to use `_.findKey({a: "A", b: "B"}, value => value === "B") // => "b"` because the 2nd argument is a predicate. The shorthand `_.findKey({...}, "B")` will look for a property called `B`: `{b: { B: ... } }` – MeltedPenguin Apr 02 '21 at 13:54
function extractKeyValue(obj, value) {
return Object.keys(obj)[Object.values(obj).indexOf(value)];
}
Made for closure compiler to extract key name which will be unknown after compilation
More sexy version but using future Object.entries
function
function objectKeyByValue (obj, val) {
return Object.entries(obj).find(i => i[1] === val);
}

- 16,093
- 5
- 70
- 73
-
8I think this is the best one for 2017+ since it uses plain JavaScript. – brainbag Feb 12 '18 at 15:46
-
-
@SamuelChen that's right but if it worked it would mean an array is needed as a result. Where `Object.entries(obj).find(i => i[1] === val);` use `filter` instead `Object.entries(obj).filter(i => i[1] === val);` – Pawel Jul 06 '19 at 09:29
-
Use destructuring to make it even better `Object.entries(obj).find( ([ key, value ]) => value === val);` – hitautodestruct Jun 15 '20 at 11:58
-
2You got the fastest solution as of 2021. Object.values(...).find(...) is 10% slower for a 15 properties object, I wonder how better that could be for a big object. – Elmatou Mar 25 '21 at 13:48
-
@Elmatou interesting observation, I didn't know that. I'm wondering if that's also true on bigger samples. The thing with benchmarking JS on small samples are very random results – Pawel Mar 28 '21 at 14:06
-
this is actually not going to return the key using the Object.entries method. Suggested edit incoming. (Arge too many pending edits) – MrMesees Dec 08 '22 at 07:36
I use this function:
Object.prototype.getKey = function(value){
for(var key in this){
if(this[key] == value){
return key;
}
}
return null;
};
Usage:
// ISO 639: 2-letter codes
var languageCodes = {
DA: 'Danish',
DE: 'German',
DZ: 'Bhutani',
EL: 'Greek',
EN: 'English',
EO: 'Esperanto',
ES: 'Spanish'
};
var key = languageCodes.getKey('Greek');
console.log(key); // EL

- 51,456
- 28
- 233
- 198
-
10+1 neat solution. But i have a question: Shouldn't you always check for `obj.hasOwnProperty(key)` or is it unnecessary in this case ? – V-Light Jun 12 '13 at 09:38
-
6Mutating the Object prototype is bad practice: https://stackoverflow.com/questions/23807805/why-is-mutating-the-prototype-of-an-object-bad-for-performance – Jon Koops Jan 06 '16 at 17:49
Non-iteratable solution
Main function:
var keyByValue = function(value) {
var kArray = Object.keys(greetings); // Creating array of keys
var vArray = Object.values(greetings); // Creating array of values
var vIndex = vArray.indexOf(value); // Finding value index
return kArray[vIndex]; // Returning key by value index
}
Object with keys and values:
var greetings = {
english : "hello",
ukranian : "привіт"
};
Test:
keyByValue("привіт");
// => "ukranian"

- 1,281
- 2
- 14
- 30
-
3simpler: `Object.keys(greetings )[Object.values(greetings ).indexOf('привіт')]` – shutsman Oct 07 '19 at 10:33
Keep your prototype clean.
function val2key(val,array){
for (var key in array) {
if(array[key] == val){
return key;
}
}
return false;
}
Example:
var map = {"first" : 1, "second" : 2};
var key = val2key(2,map); /*returns "second"*/

- 5,068
- 44
- 38
If you are working with Underscore or Lodash library, you can use the _.findKey function:
var users = {
'barney': { 'age': 36, 'active': true },
'fred': { 'age': 40, 'active': false },
'pebbles': { 'age': 1, 'active': true }
};
_.findKey(users, function(o) { return o.age < 40; });
// => 'barney' (iteration order is not guaranteed)
// The `_.matches` iteratee shorthand.
_.findKey(users, { 'age': 1, 'active': true });
// => 'pebbles'
// The `_.matchesProperty` iteratee shorthand.
_.findKey(users, ['active', false]);
// => 'fred'
// The `_.property` iteratee shorthand.
_.findKey(users, 'active');
// => 'barney'

- 8,670
- 7
- 63
- 89

- 6,091
- 1
- 21
- 25
I created the bimap library (https://github.com/alethes/bimap) which implements a powerful, flexible and efficient JavaScript bidirectional map interface. It has no dependencies and is usable both on the server-side (in Node.js, you can install it with npm install bimap
) and in the browser (by linking to lib/bimap.js).
Basic operations are really simple:
var bimap = new BiMap;
bimap.push("k", "v");
bimap.key("k") // => "v"
bimap.val("v") // => "k"
bimap.push("UK", ["London", "Manchester"]);
bimap.key("UK"); // => ["London", "Manchester"]
bimap.val("London"); // => "UK"
bimap.val("Manchester"); // => "UK"
Retrieval of the key-value mapping is equally fast in both directions. There are no costly object/array traversals under the hood so the average access time remains constant regardless of the size of the data.

- 922
- 7
- 9
-
One of the only solutions that doesn't require iteration (either in the solution itself, the standard library or another library). – Scott Rudiger Dec 23 '19 at 07:39
this worked for me to get key/value of object.
let obj = {
'key1': 'value1',
'key2': 'value2',
'key3': 'value3',
'key4': 'value4'
}
Object.keys(obj).map(function(k) {
console.log("key with value: " + k + " = " + obj[k])
})

- 2,254
- 1
- 8
- 19

- 2,331
- 23
- 25
-
That doesn't address the question, though, and in general, `map` should be used only if you need its return value--not as a general iterator – Dave Newton Mar 12 '23 at 13:50
-
This does not answer the question, that is, "get a key by its value." This answer merely show you how to iterate through an object by key. – Jason Jun 01 '23 at 20:06
didn't see the following:
const obj = {
id: 1,
name: 'Den'
};
function getKeyByValue(obj, value) {
return Object.entries(obj).find(([, name]) => value === name);
}
const [ key ] = getKeyByValue(obj, 'Den');
console.log(key)

- 562
- 10
- 18
Since the values are unique, it should be possible to add the values as an additional set of keys. This could be done with the following shortcut.
var foo = {};
foo[foo.apple = "an apple"] = "apple";
foo[foo.pear = "a pear"] = "pear";
This would permit retrieval either via the key or the value:
var key = "apple";
var value = "an apple";
console.log(foo[value]); // "apple"
console.log(foo[key]); // "an apple"
This does assume that there are no common elements between the keys and values.

- 7,661
- 4
- 37
- 39
-
1One of the only solutions that doesn't require iteration (either in the solution itself, the standard library or another library). – Scott Rudiger Dec 23 '19 at 07:40
-
1The OP did say that key/value pairs were all unique therefore this low-tech answer is just fantastic! Well done ;) – customcommander Jan 22 '20 at 23:42
Given input={"a":"x", "b":"y", "c":"x"}
...
- To use the first value (e.g.
output={"x":"a","y":"b"}
):
input = {
"a": "x",
"b": "y",
"c": "x"
}
output = Object.keys(input).reduceRight(function(accum, key, i) {
accum[input[key]] = key;
return accum;
}, {})
console.log(output)
- To use the last value (e.g.
output={"x":"c","y":"b"}
):
input = {
"a": "x",
"b": "y",
"c": "x"
}
output = Object.keys(input).reduce(function(accum, key, i) {
accum[input[key]] = key;
return accum;
}, {})
console.log(output)
- To get an array of keys for each value (e.g.
output={"x":["c","a"],"y":["b"]}
):
input = {
"a": "x",
"b": "y",
"c": "x"
}
output = Object.keys(input).reduceRight(function(accum, key, i) {
accum[input[key]] = (accum[input[key]] || []).concat(key);
return accum;
}, {})
console.log(output)

- 4,481
- 3
- 22
- 41

- 2,441
- 1
- 16
- 25
-
1this is definitely the best answer , but i was scratching my head over a way to transform it in order to return only the key for a given object, ie be functionnally equivalent to indexOf for an array. – Souhaieb Besbes Apr 13 '16 at 10:28
-
Unless memory is a constraint and you are willing to spend a lot of processing power to look through the object many times over, just save the "output" as indicated above to a variable and look up the result in there... like `output['x']` . Is that what you were asking? – Fabio Beltramini Apr 16 '16 at 19:17
This is a small extension to the Underscorejs method, and uses Lodash instead:
var getKeyByValue = function(searchValue) {
return _.findKey(hash, function(hashValue) {
return searchValue === hashValue;
});
}
FindKey will search and return the first key which matches the value.
If you want the last match instead, use FindLastKey instead.

- 18,961
- 8
- 72
- 100
ES6 methods:
Object.fromEntries(Object.entries(a).map(b => b.reverse()))['value_you_look_for']

- 107
- 5
Here's a Lodash solution to this that works for flat key => value object, rather than a nested object. The accepted answer's suggestion to use _.findKey
works for objects with nested objects, but it doesn't work in this common circumstance.
This approach inverts the object, swapping keys for values, and then finds the key by looking up the value on the new (inverted) object. If the key isn't found then false
is returned, which I prefer over undefined
, but you could easily swap this out in the third parameter of the _.get
method in getKey()
.
// Get an object's key by value
var getKey = function( obj, value ) {
var inverse = _.invert( obj );
return _.get( inverse, value, false );
};
// US states used as an example
var states = {
"AL": "Alabama",
"AK": "Alaska",
"AS": "American Samoa",
"AZ": "Arizona",
"AR": "Arkansas",
"CA": "California",
"CO": "Colorado",
"CT": "Connecticut",
"DE": "Delaware",
"DC": "District Of Columbia",
"FM": "Federated States Of Micronesia",
"FL": "Florida",
"GA": "Georgia",
"GU": "Guam",
"HI": "Hawaii",
"ID": "Idaho",
"IL": "Illinois",
"IN": "Indiana",
"IA": "Iowa",
"KS": "Kansas",
"KY": "Kentucky",
"LA": "Louisiana",
"ME": "Maine",
"MH": "Marshall Islands",
"MD": "Maryland",
"MA": "Massachusetts",
"MI": "Michigan",
"MN": "Minnesota",
"MS": "Mississippi",
"MO": "Missouri",
"MT": "Montana",
"NE": "Nebraska",
"NV": "Nevada",
"NH": "New Hampshire",
"NJ": "New Jersey",
"NM": "New Mexico",
"NY": "New York",
"NC": "North Carolina",
"ND": "North Dakota",
"MP": "Northern Mariana Islands",
"OH": "Ohio",
"OK": "Oklahoma",
"OR": "Oregon",
"PW": "Palau",
"PA": "Pennsylvania",
"PR": "Puerto Rico",
"RI": "Rhode Island",
"SC": "South Carolina",
"SD": "South Dakota",
"TN": "Tennessee",
"TX": "Texas",
"UT": "Utah",
"VT": "Vermont",
"VI": "Virgin Islands",
"VA": "Virginia",
"WA": "Washington",
"WV": "West Virginia",
"WI": "Wisconsin",
"WY": "Wyoming"
};
console.log( 'The key for "Massachusetts" is "' + getKey( states, 'Massachusetts' ) + '"' );
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

- 8,851
- 3
- 54
- 46
Here is my solution first:
For example, I suppose that we have an object that contains three value pairs:
function findKey(object, value) {
for (let key in object)
if (object[key] === value) return key;
return "key is not found";
}
const object = { id_1: "apple", id_2: "pear", id_3: "peach" };
console.log(findKey(object, "pear"));
//expected output: id_2
We can simply write a findKey(array, value) that takes two parameters which are an object and the value of the key you are looking for. As such, this method is reusable and you do not need to manually iterate the object every time by only passing two parameters for this function.

- 31
- 2
var a = new Array();
a.push({"1": "apple", "2": "banana"});
a.push({"3": "coconut", "4": "mango"});
GetIndexByValue(a, "coconut");
function GetIndexByValue(arrayName, value) {
var keyName = "";
var index = -1;
for (var i = 0; i < arrayName.length; i++) {
var obj = arrayName[i];
for (var key in obj) {
if (obj[key] == value) {
keyName = key;
index = i;
}
}
}
//console.log(index);
return index;
}

- 1,712
- 6
- 32
- 42
-
@Fr0zenFyr : Following link can answer you question better - http://stackoverflow.com/questions/8423493/what-is-the-performance-of-objects-arrays-in-javascript-specifically-for-googl – Atur Jun 11 '15 at 05:42
Or, easier yet - create a new object with the keys and values in the order you want then do look up against that object. We have had conflicts using the prototype codes above. You don't have to use the String function around the key, that is optional.
newLookUpObj = {};
$.each(oldLookUpObj,function(key,value){
newLookUpObj[value] = String(key);
});

- 8,901
- 4
- 17
- 18
I typically recommend lodash rather than underscore.
If you have it, use it.
If you don't, then you should consider using the lodash.invert npm package, which is pretty tiny.
Here's how you can test it using gulp:
1) Create a file called gulpfile.js with the following contents:
// Filename: gulpfile.js
var gulp = require('gulp');
var invert = require('lodash.invert');
gulp.task('test-invert', function () {
var hash = {
foo: 1,
bar: 2
};
var val = 1;
var key = (invert(hash))[val]; // << Here's where we call invert!
console.log('key for val(' + val + '):', key);
});
2) Install the lodash.invert package and gulp
$ npm i --save lodash.invert && npm install gulp
3) Test that it works:
$ gulp test-invert
[17:17:23] Using gulpfile ~/dev/npm/lodash-invert/gulpfile.js
[17:17:23] Starting 'test-invert'...
key for val(1): foo
[17:17:23] Finished 'test-invert' after 511 μs
References
https://www.npmjs.com/package/lodash.invert
As if this question hasn't been beaten to a pulp...
Here's one just for whatever curiosity it brings you...
If you're sure that your object will have only string values, you could really exhaust yourself to conjure up this implementation:
var o = { a: '_A', b: '_B', c: '_C' }
, json = JSON.stringify(o)
, split = json.split('')
, nosj = split.reverse()
, o2 = nosj.join('');
var reversed = o2.replace(/[{}]+/g, function ($1) { return ({ '{':'}', '}':'{' })[$1]; })
, object = JSON.parse(reversed)
, value = '_B'
, eulav = value.split('').reverse().join('');
console.log('>>', object[eulav]);
Maybe there's something useful to build off of here...
Hope this amuses you.

- 9,785
- 4
- 61
- 46
Underscore js solution
let samplLst = [{id:1,title:Lorem},{id:2,title:Ipsum}]
let sampleKey = _.findLastIndex(samplLst,{_id:2});
//result would be 1
console.log(samplLst[sampleKey])
//output - {id:2,title:Ipsum}

- 356
- 2
- 11
If you have an object with array values. Here is a good example. Let us suppose you want to show an icon based on the extension of the file you have. All the extensions with the same icon go under the same object value.
Note: wrap the cases here in an object is better than do a switch with a lot of cases.
Check the code snippet below (written in es6) to see how we return the specific key for the specific extension.
I got the list of extensions from this git repo
// Oject that contains different icons for different extentions
const icons = {
"music": ["mp3", "m4a", "ogg", "acc", "flac","m3u", "wav"],
"video": ["mp4","webm", "mkv", "avi", "mov", "m4v", "mpeg"],
"image": ["jpg", "gif", "png", "jpeg", "tif", "psd", "raw", "ico"],
"archives": ["zip", "rar", "tar", "dmg", "jar"],
"3d-files": ["3ds", "dwg", "obj", "dae", "skp", "fbx"],
"text": ["doc", "rtf", "txt", "odt", "tex"],
"vector-graphics":["ai", "svg"],
"pdf": ["pdf"],
"data": ["xml", "csv", "xls"]
}
const get_icon_Key =( icons_object,file_extention) => {
// For each key we chack if the value is contained in the list of values
let key = Object.keys(icons_object).find(
k=> icons[k].find(
// At this leve we check if the extention exist in the array of the specific object value ie. 'music', 'video' ...
icons_ext => icons_ext === file_extention)
// if we find it means this is the key we are looking for
? true: false);
return key
}
console.log(`The icon of for mp3 extention is: => ${get_icon_Key(icons,"mp3")}`)
console.log(`The icon of for mp4 extention is: => ${get_icon_Key(icons,"mp4")}`)

- 7,074
- 10
- 69
- 74
-
Why are you referencing the outer icons object in the function if you pass it in any way as icons_object? – David Axelrod Feb 15 '22 at 18:47
Came here (in 2022) looking for a close variation of OP's question. Variation:
How to find an object key based on a value, where keys may hold collections of values?
For this use case, switch from equality (===
) to .includes()
:
const foo = ['a', 'b','c'];
const bar = ['x', 'y', 'z'];
const bat = [2, 5, 'z'];
const obj = {foo: foo, bar: bar, bat: bat};
const findMe = (v) => {
return Object.keys(obj).filter((k) => obj[k].includes(v))
}
findMe('y') // ['bar']
findMe('z') // ['bar', 'bat']

- 20,390
- 3
- 33
- 58
Really straightforward.
const CryptoEnum = Object.freeze({
"Bitcoin": 0, "Ethereum": 1,
"Filecoin": 2, "Monero": 3,
"EOS": 4, "Cardano": 5,
"NEO": 6, "Dash": 7,
"Zcash": 8, "Decred": 9
});
Object.entries(CryptoEnum)[0][0]
// output => "Bitcoin"

- 289
- 2
- 11
I know I’m late but what do you think about this EMCMAScript 2017 solution I made today ? It handles multiple matchs because what happens if two keys have the same values ? This is why I created this little snippet.
When there’s one match, it returns just a string but when there are several matchs, it returns an array.
let object = { nine_eleven_was_a_inside_job: false, javascript_isnt_useful: false }
// Complex, dirty but useful. Handle mutiple matchs which is the main difficulty.
Object.prototype.getKeyByValue = function (val) {
let array = [];
let array2 = [];
// Get all the key in the object.
for(const [key] of Object.entries(this)) {
if (this[key] == val) {
// Putting them in the 1st array.
array.push(key)
}
}
// List all the value of the 1st array.
for(key of array) {
// "If one of the key in the array is equal to the value passed in the function (val), it means that 'val' correspond to it."
if(this[key] == val) {
// Push all the matchs.
array2.push(key);
}
}
// Check the lenght of the array.
if (array2.length < 2) {
// If it's under 2, only return the single value but not in the array.
return array2[0];
} else {
// If it's above or equal to 2, return the entire array.
return array2;
}
}
/*
Basic way to do it wich doesn't handle multiple matchs.
let getKeyByValue = function (object, val) {
for(const [key, content] of Object.entries(object)) {
if (object[key] === val) {
return key
}
}
}
*/
console.log(object.getKeyByValue(false))

- 33
- 1
- 6
We can use simple function to get the value passed key something below
const getKeyByValue = (object, value) => Object.keys(object).find(key => object[key] === value)

- 18,210
- 6
- 124
- 133
Keep it simple!
You don't need to filter the object through sophisticated methods or libs, Javascript has a built in function called Object.values.
Example:
let myObj = {jhon: {age: 20, job: 'Developer'}, marie: {age: 20, job:
'Developer'}};
function giveMeTheObjectData(object, property) {
return Object.values(object[property]);
}
giveMeTheObjectData(myObj, 'marie'); // => returns marie: {}
This will return the object property data.
References
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/values

- 9,119
- 2
- 23
- 29