user2486790
user2486790

Reputation: 11

Argument in reference

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

Answers (2)

PSL
PSL

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

http://jsfiddle.net/RuCnU/

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

Upvotes: 4

Andrew Clark
Andrew Clark

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

Related Questions