Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value in an object's key using a variable referencing that key?

Tags:

javascript

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?

like image 278
Chameron Avatar asked Feb 15 '11 07:02

Chameron


People also ask

How do you use the value of a variable as a object key?

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!

How do I find a specific key in an object?

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.

How do I find the index of an object in a key?

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] .


2 Answers

Use [] notation for string representations of properties:

console.log(obj[name]); 

Otherwise it's looking for the "name" property, rather than the "a" property.

like image 151
David Tang Avatar answered Sep 27 '22 19:09

David Tang


obj["a"] is equivalent to obj.a so use obj[name] you get "A"

like image 32
Longda Avatar answered Sep 27 '22 18:09

Longda