1

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?

asked Jun 14, 2013 at 16:17
1
  • Must mention that argument "obj1" must be string ! Commented Jun 14, 2013 at 16:20

2 Answers 2

4

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
 }
}

http://jsfiddle.net/RuCnU/

This Link can provide you some basic insight on object and keys.

answered Jun 14, 2013 at 16:18
Sign up to request clarification or add additional context in comments.

Comments

1
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"}.

answered Jun 14, 2013 at 16:18

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.