0

Say I have a JavaScript object like so:

var myObject = {
  key1: "value1",
  key2: "value2",
  key3: "value3"
}

We all know I can get value1 by using myObject ['key1'], but is there any way to do the reverse, like myObject ["value1"] returning 'key1'?

I understand that I can use

var values = Object.values (myObject);
var index = values.indexOf ("value1");
var keys = Object.keys (myObject);
keys [index];

to do this, but that's just long-winded. I also understand that this would be even more cumbersome when multiple keys have the same value. I'm just wondering if there is some other way to make doing something like this easier.

2 Answers2

3

I'd make an object that reverses the keys and values, then use ordinary property lookup:

var myObject = {
  key1: "value1",
  key2: "value2",
  key3: "value3"
}
var reversedObj = Object.fromEntries(
  Object.entries(myObject).map(entries => entries.reverse())
);

console.log(reversedObj.value1);
console.log(reversedObj.value3);

Though, keep in mind that this depends on the values being unique.

If you need to distinguish string values from non-string values, eg key1: 123 vs key2: '123', use a Map instead (since plain objects can only have string (and symbol) keys, but Map keys can be any type)

var myObject = {
  key1: 123,
  key2: "123",
  key3: "value3"
}
var reversedMap = new Map(
  Object.entries(myObject).map(entries => entries.reverse())
);

console.log(reversedMap.get('123'));
console.log(reversedMap.get(123));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

Sure, you can iterate over keys and filter by values: Values don't have to be unique, you will get an array of keys. And you don't have to reverse an object beforehand.

const obj = {a: 1, b: 2};
const value = 1;
const keys = Object.keys(obj).filter(key => obj[key] === value);
console.log(keys);
Roberto Zvjerković
  • 9,657
  • 4
  • 26
  • 47