Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: access to an object's member by name

Tags:

javascript

I have an object called themesData:

var themesData = {}
themesData.a = { key: "value" }; 
themesData.b = { key: "another value"};

...and I want to access one of the members by its name. I get a string which contains either "a" or "b" and I want to get the appropriate member's value.

I'd be happy to get some help on that.

like image 945
Nir Avatar asked Jan 25 '10 14:01

Nir


People also ask

How do you access object members?

Use the member-access operator ( . ) between the object variable name and the member name. If the member is Shared, you do not need a variable to access it.

How do you use a variable to access the object property?

Answer: Use the Square Bracket ( [] ) Notationnotation, like obj. foo , and the square bracket ( [] ) notation, like obj[foo] . Where the dot notation is easier to read and write, the square bracket notation offers much more flexibility since the value between the brackets can be any variable or expression.

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.


1 Answers

themesData["a"].key does what you need and is equivalent to themesData.a.key, still the "array index style" notation allows you to dynamically generate index names.

like image 167
naivists Avatar answered Oct 06 '22 04:10

naivists