Home >Web Front-end >JS Tutorial >How Can I Retrieve a JavaScript Object's Key by Its Value?
JavaScript objects provide an efficient way to store data as key-value pairs. However, there may be situations where you need to retrieve the key associated with a specific value. This task can be accomplished with ease using a simple function.
To retrieve the key for a given value, you can utilize the getKeyByValue() function, defined as follows:
function getKeyByValue(object, value) { return Object.keys(object).find(key => object[key] === value); }
This function leverages the built-in Object.keys() method to obtain an array of all keys in the object. It then employs the Array.find() method to iterate over the keys and check if any of their corresponding values match the specified value. If a matching key is found, it is returned as the result.
The provided function is fully compliant with ES6 standards and does not require modifications to any prototypes or external libraries. Here's an example of its usage:
const map = { "first": "1", "second": "2" }; console.log(getKeyByValue(map, "2")); // Outputs: "second"
In this example, the map object stores two key-value pairs. The getKeyByValue() function is used to retrieve the key associated with the value "2", which is "second". The function efficiently locates the key and outputs it to the console.
The above is the detailed content of How Can I Retrieve a JavaScript Object's Key by Its Value?. For more information, please follow other related articles on the PHP Chinese website!