1

So, I hvae following object in js:

var values= {
  'first'       : '42',
  'last'        : '43',
};

How do I get the key from the value?

For example, I have 42 and would like to get first as the result. Thanks!

HEYHEY
  • 533
  • 4
  • 13

2 Answers2

1

You can use Object.keys() method

Object.keys(values).filter(function(key) {return values[key] === '42'})[0];
Vladu Ionut
  • 8,075
  • 1
  • 19
  • 30
  • Thank you. So, I have this : `var cuc_k = Object.keys(values);`. I read the info on the link you sent me. Do you know how I can choose a specific key? For example, the key for value of "42" – HEYHEY Feb 25 '16 at 09:12
  • i've updated my answer – Vladu Ionut Feb 25 '16 at 09:16
1

Simple for loop will help you:

var values= {
  first: '42',
  last: '43',
};

var val = '42', key;

for (key in values) {
  if (values[key] == val) break;
}

document.write(key);
dfsq
  • 191,768
  • 25
  • 236
  • 258