2

This looks like a very simple issue, but I just can't get it to work.

I have a Javascript object like this:

var person = {};
person.one = {gender: 'male', name: 'John'};
person.two = {gender: 'male', name: 'Doe'};
person.three = {gender: 'female', name: 'Jane'};

Then I have some HTML like so:

<a id="one">click</a>
<a id="two">click</a>
<a id="three">click</a>

Now, I need to get the correct object value by the id of the clicked link. So basically, I need to dynamically access the 1st-level object keys without a for-loop, since the keys are strings.

I've tried this:

$('a').click(function() {
   alert(person[$(this).attr('id')['gender']]);
});

It didn't work. Neither did this:

$('a').click(function() {
   alert(person.($(this).attr('id')).gender);
});

All I get back is an "uncaught exception: Syntax error, unrecognized expression". Obviously, my syntax is way off.

I've already read through many posts on here, but couldn't find the solution. Any ideas?

1
  • your first example didnt work because you put the first closing brace in the wrong place. person[$(this).attr('id')]['gender'] Commented May 26, 2010 at 23:10

3 Answers 3

3

To access a property with a dynamic name like you're going for, the correct syntax is to use brackets, like an array.

alert(person[$(this).attr('id')].gender);

Or it might just be cleaner-looking to pull that ID into a separate variable:

var id = $(this).attr('id');
alert(person[id].gender);

Your call :)

Sign up to request clarification or add additional context in comments.

Comments

3

Try:

$('a').click(function() {
   alert(person[$(this).attr('id')]['gender']);
});

You had your square brackets in the wrong spot.

Comments

2

Try alert(person[$(this).attr('id')].gender)

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.