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
.
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.
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.
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.
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 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
}
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With