I have an object and I can reference key a
as in the following:
var obj = { a: "A", b: "B", c: "C" } console.log(obj.a); // return string : A
I want to get the value by using a variable to reference the object key as below:
var name = "a"; console.log(obj.name) // this prints undefined, but I want it to print "A"
How can I do this?
Use bracket notation to get an object's value by a variable key, e.g. obj[myVar] . The variable or expression in the brackets gets evaluated, so if a key with the computed name exists, you will get the corresponding value back. Copied!
There are mainly two methods to check the existence of a key in JavaScript Object. The first one is using “in operator” and the second one is using “hasOwnProperty() method”. Method 1: Using 'in' operator: The in operator returns a boolean value if the specified property is in the object.
To get an object's key by index, call the Object. keys() method to get an array of the objects keys and use bracket notation to access the key at the specific index, e.g. Object. keys(obj)[1] .
Use []
notation for string representations of properties:
console.log(obj[name]);
Otherwise it's looking for the "name" property, rather than the "a" property.
obj["a"]
is equivalent to obj.a
so use obj[name]
you get "A"
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