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?

29 s
29

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"));

Leave a Reply

Your email address will not be published. Required fields are marked *