user765368
user765368

Reputation: 20346

Get object property name from value

Let's say that I have a JavaScript object like this:

var obj = {
    a: 1, 
    b: 2, 
    c: 3,
    d: 4
};

How do I get the property c of the object for example knowing the value 3?

Upvotes: 0

Views: 70

Answers (2)

passer
passer

Reputation: 644

try something like iterating the object?

for(var property in obj) 
{
  if(obj.hasOwnProperty(property) ) 
  {
    if(obj[property] === value)
      return property;
  }
}

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

There is no built-in method to do this, but you can easily write one

var obj = {
    a: 1,
    b: 2,
    c: 3,
    d: 4
};
var key;
for (var x in obj) {
    if (obj.hasOwnProperty(x) && obj[x] == 3) {
        key = x;
        break;
    }
}
console.log(key)

Demo: Fiddle

Upvotes: 1

Related Questions