Home >Web Front-end >JS Tutorial >How to Retrieve a JavaScript Object's Key Based on its Value?
Handling key-value pairs is a common scenario when working with objects in JavaScript. In certain situations, it becomes necessary to retrieve the key associated with a specific value. Here's a complete guide to accomplish this task effectively:
Function to Retrieve Key by Value
To obtain the key by its value, you can utilize the following function:
function getKeyByValue(object, value) { return Object.keys(object).find(key => object[key] === value); }
This function accepts two parameters: the object and the value you want to search for. It iterates through the object's keys and checks if the value at each key matches the input value. If a match is found, it returns the corresponding key.
ES6 Compatibility
The function provided is fully compatible with ES6 and does not mutate the original object or require external libraries.
Example Usage
Consider the following example:
const map = {"first" : "1", "second" : "2"}; console.log(getKeyByValue(map, "2")); // Outputs "second"
In this example, we search for the key associated with the value "2" in the map object. The function correctly returns "second" as the result.
The above is the detailed content of How to Retrieve a JavaScript Object's Key Based on its Value?. For more information, please follow other related articles on the PHP Chinese website!