0

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?

2
  • 2
    The only solution I see is to iterate through the object and find the key Commented Nov 20, 2013 at 3:57
  • 3
    Possible duplicate: stackoverflow.com/questions/9907419/… Commented Nov 20, 2013 at 3:58

2 Answers 2

1

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

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

2 Comments

obj.hasOwnProperty(x) what's the need of doing this check.? x inside that for must be a key from that object obj right?
it is to handle if it has prototypical inherited properties
1

try something like iterating the object?

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.