Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a key in a JavaScript object by its value?

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?

like image 663
arik Avatar asked Mar 28 '12 12:03

arik


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 find the key of an object?

Use object. keys(objectName) method to get access to all the keys of object.

How do you get a key in a value pair?

In order to get a key-value pair from a KiiObject, call the get() method of the KiiObject class. Specify the key for the value to get as the argument of the get() method.


1 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"));
like image 182
UncleLaz Avatar answered Sep 28 '22 06:09

UncleLaz