3

I have:

if (!myObj.login_id) { 
    alert("The object for login_id does not exist.");
} else {
    alert("The object for login_id DOES exist. The value of the object is: " + myObj.login_id);
}

This is working properly. The object and it's value are defined already. However, I have multiple objects which are named after their ID attr. So, I try doing this (say for example this is a click event:

objtitle = $(this).attr('id'); // this is "login_id"

if (!myObj.objtitle) {
    alert("The object for "+objtitle+" does not exist.");   
} else {
    alert("The object for "+objtitle+" DOES exist. The value of the object is: " + myObj.objtitle);
}

Why does it stop working when I use a variable for the name of the object?

1
  • 1
    if ( !myObj[ this.id ] ) { ... Commented Oct 3, 2011 at 15:31

2 Answers 2

10

Use square brackets.

myObj[objtitle]
Sign up to request clarification or add additional context in comments.

1 Comment

Just seeing how I can thank someone for helping me out on here. I clicked "this information is useful" and "this is your accepted answer"... thanks also to lonesomeday!
4

There are two ways of accessing an object's properties: the dot syntax and the square bracket syntax. These are called member operators. So the following two are equivalent:

obj.foo
obj['foo']

The dot syntax (the first one) is a literal name. obj.objtitle therefore attempts to find a property called objtitle. If you have a variable containing the property name you want, you have to use the square bracket syntax.

myObj[objtitle]

Comments

Your Answer

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.