How to get a key in a JavaScript object by its value?

arik :

I have a quite simple JavaScript object, which I use as an associative array. Is there a simple function allowing me to get the key for a value, or do I have to iterate the object and find it out manually?

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

ES6, no prototype mutations or external libraries.

Example,

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


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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to check if a key exists in Json Object and get its value

How to get a key in a JavaScript Map by its value?

How to get key dan value in multidimentional javascript object

How to get the path from javascript object from key and value

How to Get the Value of nested JavaScript object property by string key

How can I get the key name and its value from an array within a JSON object

how to get specific key value from object in javascript?

How to get Key and Value from JSON object in Javascript(Postman)

How can I get a key in a JavaScript 'Map' by its value?

javascript - How to show value from object by matching user input to its key?

How to Sort object arrays by its key value

Get the value based on object key in javascript

How do I get a key value of each object in a javascript object?

how to get object by key and value

How to get a value of a object from its foreign key?

get key from a javascript object with minimum value

Javascript get value from object based on key compared to its size smaller then next key

How to get key and value of object in javascript?

How to get a key from array of objects by its value Javascript

How can I get the string value of a key for a JavaScript object?

how to get specific key and its value from object

Get a key in a JavaScript object by its value and rename it

how to get the object key if the object and array value matches in javascript

How can I get the value of a sibling key in a javascript object?

JavaScript Map: How to find a key, get its value, and display it in HTML?

How to get the value referring to a specific key in the object and its children?

How to get a value in a JavaScript object by key

Typescript, How to get the value of an object based on its key?

How to get object key if their value matched with our variable in JavaScript?