bobsoap
bobsoap

Reputation: 5104

Javascript object key by element id? (jQuery)

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?

Upvotes: 2

Views: 2816

Answers (3)

Matchu
Matchu

Reputation: 85794

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 :)

Upvotes: 3

Stefan Kendall
Stefan Kendall

Reputation: 67802

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

Upvotes: 2

steve_c
steve_c

Reputation: 6255

Try:

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

You had your square brackets in the wrong spot.

Upvotes: 3

Related Questions