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?
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?
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
obj.hasOwnProperty(x) what's the need of doing this check.? x inside that for must be a key from that object obj right?