Borislav Hadzhiev
Fri Oct 29 2021·2 min read
Photo by Alexandre Chambon
To get an object's key by it's value, call the Object.keys()
method to get
an array of the object's keys. Then 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.
function getObjKey(obj, value) { return Object.keys(obj).find(key => obj[key] === value); } const obj = {country: 'Chile', city: 'Santiago'}; console.log(getObjKey(obj, 'Chile')); // 👉️ "country"
We used the Object.keys method to get an array containing the object's keys.
const obj = {country: 'Chile', city: 'Santiago'}; console.log(Object.keys(obj)); // 👉️ ['country', 'city']
Then, we called the Array.find method on the keys array.
find
method gets called with each element (key) in the array until it returns a truthy value or iterates over the entire array.On each iteration, we use the key to access the object's value and compare it to the supplied value.
If equality check succeeds, the find
method returns the corresponding key and
short-circuits.
If the equality check never returns true
, the find
method will return
undefined
.
function getObjKey(obj, value) { return Object.keys(obj).find(key => obj[key] === value); } const obj = {country: 'Chile', city: 'Santiago'}; console.log(getObjKey(obj, 'DoesNotExist')); // 👉️ undefined
find
method returns the first element that satisfies the testing function. If you have multiple keys with the same value, you would get the name of the first key.function getObjKey(obj, value) { return Object.keys(obj).find(key => obj[key] === value); } const obj = {city1: 'Santiago', city2: 'Santiago'}; console.log(getObjKey(obj, 'Santiago')); // 👉️ "city1"
If you need to get the values of multiple keys that store the same value, you
can switch the find
method to filter
.
function getObjKeys(obj, value) { return Object.keys(obj).filter(key => obj[key] === value); } const obj = {city1: 'Santiago', city2: 'Santiago'}; // 👇️️ ["city1", "city2"] console.log(getObjKeys(obj, 'Santiago'));
By using the Array.filter method, we get an array of the keys that satisfy the condition.
The function we passed to the filter
method gets called for each key in the
array and does not short-circuit on the first truthy response.