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?
-
Must mention that argument "obj1" must be string !Ivan Chernykh– Ivan Chernykh2013年06月14日 16:20:49 +00:00Commented Jun 14, 2013 at 16:20
2 Answers 2
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.
Comments
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"}.