Home >Web Front-end >JS Tutorial >How to Retrieve a JavaScript Object's Key Based on its Value?

How to Retrieve a JavaScript Object's Key Based on its Value?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-11 13:31:11172browse

How to Retrieve a JavaScript Object's Key Based on its Value?

Retrieving Keys Based on Values in JavaScript Objects

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn