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.

1
  • Why don't you just flip the key/values? Commented Jul 18, 2019 at 9:45

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Wow. Thank you for the quick response. This is exactly what I was looking for.
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);

3 Comments

Thanks. This will be great to use when the values aren't unique.
If you want just one value you can replace filter with find.
No problem. Keep in mind the accepted answer doesn't work with numerical values and it's much slower.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.