Home >Web Front-end >JS Tutorial >How to Find a JavaScript Object's Key by Its Value?

How to Find a JavaScript Object's Key by Its Value?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-08 17:07:14241browse

How to Find a JavaScript Object's Key by Its Value?

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:

  • No alterations to object prototypes
  • Eschews external libraries
  • Exceptionally succinct syntax

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!

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