Javascript get Object Property Name

I passed the following object:

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

I want to pull the typeA key from the above structure.

This value can change every time, so the next time it can be typeB .

So, I would like to know if there is a way to do something like the following pseudocode:

 var theTypeIs = myVar.key(); 

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

+59
javascript
Mar 21 '14 at 17:06
source share
3 answers

If you know for sure that there will always be only one key in an object, you can use Object.keys :

 theTypeIs = Object.keys(myVar)[0]; 
+116
Mar 21 '14 at 17:09
source share

Like other answers, you can do theTypeIs = Object.keys(myVar)[0]; to get the first key. If you expect 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 } }); 
+17
Mar 21 '14 at 17:57
source share

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

 var result = Object.keys(myVar); alert(result[0]) // result[0] alerts typeA 
+14
Mar 21 '14 at 17:09
source share



All Articles