How to Locate a Key by Its Associated Value in a JavaScript Object
In situations where a JavaScript object serves as an associative array, retrieving the key corresponding to a particular value becomes a common requirement. Iterating through the object manually may seem like the only option, but a more efficient solution lies in utilizing a concise function.
Solution:
Thankfully, the ES6 implementation offers an elegant approach:
function getKeyByValue(object, value) { return Object.keys(object).find(key => object[key] === value); }
This function leverages the Object.keys(object) method to retrieve an array of all keys in the given object. Subsequently, it employs the Array.find() method to iterate through the keys and locate the one whose corresponding value matches the specified value.
Features:
Example:
Consider the example below:
const map = {"first" : "1", "second" : "2"}; console.log(getKeyByValue(map,"2")); // Output: "second"
In this instance, the function returns "second," as it is the key associated with the value "2" in the 'map' object.
The above is the detailed content of How to Find a JavaScript Object's Key by Its Value?. For more information, please follow other related articles on the PHP Chinese website!