Reputation: 5104
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
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
Reputation: 6255
Try:
$('a').click(function() {
alert(person[$(this).attr('id')]['gender']);
});
You had your square brackets in the wrong spot.
Upvotes: 3