Reputation: 11
I have an object:
obj = {
obj1: {
name: "Test";
}
}
and function:
var anon = function(a) {
alert(obj.a.name);
}
I want to give as an argument "obj1". Im newbie to programming so I think I should get alert with "Test" but it doesn't work. How to give reference with argument?
Upvotes: 1
Views: 51
Reputation: 123739
You can do this way: You can always access properties of the object as obj[key]
, thats what we are doing here.
var anon = function(a) {
alert(obj[a].name);
}
and remove ;
from the inline object property definision syntax.
obj = {
obj1: {
name: "Test"; //<-- Here
}
}
This Link can provide you some basic insight on object and keys.
Upvotes: 4
Reputation: 208665
var anon = function(a) {
alert(obj[a].name);
}
When you are looking up the property of an object using a string use square brackets, the obj.a
will only work if the object has a property named a
, for example obj = {a: "Test"}
.
Upvotes: 1