Home >Web Front-end >JS Tutorial >How Can I Reverse Key-Value Lookups in JavaScript?

How Can I Reverse Key-Value Lookups in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-12-10 05:25:16232browse

How Can I Reverse Key-Value Lookups in JavaScript?

Reversing Key-Value Relationships in JavaScript

In JavaScript, associating values with unique keys is often achieved using objects. However, situations may arise where you need to retrieve the key based on its corresponding value. Here's how you can achieve this:

Custom Function with Object.keys()

Leveraging the Object.keys() method, which returns an array of object keys, we can iterate over them and search for the key whose value matches the specified value. Here's a neat function to do just that:

function getKeyByValue(object, value) {
  return Object.keys(object).find(key => object[key] === value);
}

This function takes an object and the value you're looking for as arguments. It uses Object.keys() to obtain an array of keys, and then checks each key's value against the input value. Upon finding a match, it returns the corresponding key.

Example Usage

Consider the following object and value:

const map = {"first": "1", "second": "2"};
const result = getKeyByValue(map, "2");

Output:

"second"

In this example, the getKeyByValue function returns "second" as it's the key with the value "2" in the map object.

The above is the detailed content of How Can I Reverse Key-Value Lookups in JavaScript?. 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