Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript get Object property Name

Tags:

javascript

I passed the following object:

var myVar = { typeA: { option1: "one", option2: "two" } }

I want to be able to pull out the key typeA from the above structure.

This value can change each time so next time it could be typeB.

So I would like to know if there is a way for me to do something like the following pseudo code:

var theTypeIs = myVar.key();

This way when I can pass this object and I can pull out the first value of the object, in this case it is typeA and then based on that I can do different things with option1 and option2.

like image 269
user3447415 Avatar asked Mar 21 '14 17:03

user3447415


People also ask

How can you read properties of an object in JavaScript?

We can use the jQuery library function to access the properties of Object. jquery. each() method is used to traverse and access the properties of the object.

How do I find the key name of an object?

Use object. keys(objectName) method to get access to all the keys of object. Now, we can use indexing like Object. keys(objectName)[0] to get the key of first element of object.

How is an object property referenced?

Objects are assigned and copied by reference. In other words, a variable stores not the “object value”, but a “reference” (address in memory) for the value. So copying such a variable or passing it as a function argument copies that reference, not the object itself.


3 Answers

If you know for sure that there's always going to be exactly one key in the object, then you can use Object.keys:

theTypeIs = Object.keys(myVar)[0];
like image 129
zzzzBov Avatar answered Oct 17 '22 06:10

zzzzBov


Like the other answers you can do theTypeIs = Object.keys(myVar)[0]; to get the first key. If you are expecting more keys, you can use

Object.keys(myVar).forEach(function(k) {
    if(k === "typeA") {
        // do stuff
    }
    else if (k === "typeB") {
        // do more stuff
    }
    else {
        // do something
    }
});
like image 28
dopplesoldner Avatar answered Oct 17 '22 05:10

dopplesoldner


If you want to get the key name of myVar object then you can use Object.keys() for this purpose.

var result = Object.keys(myVar); 

alert(result[0]) // result[0] alerts typeA
like image 15
Suman Bogati Avatar answered Oct 17 '22 06:10

Suman Bogati