Hallo all. I got a javascript object with some propeties let's say
function Animal() {
this.id;
this.name;
I need to call id function in a dynamic way to get and set its value: something like this
Animal animal = new Animal();
var propertyName = "id";
animal.+propertyName = "name";
Is there an elegant way to do it? With jQuery?
Kind regards
Massimo
Hallo all. I got a javascript object with some propeties let's say
function Animal() {
this.id;
this.name;
I need to call id function in a dynamic way to get and set its value: something like this
Animal animal = new Animal();
var propertyName = "id";
animal.+propertyName = "name";
Is there an elegant way to do it? With jQuery?
Kind regards
Massimo
Share Improve this question edited Apr 1, 2010 at 8:51 Andy E 345k86 gold badges480 silver badges450 bronze badges asked Apr 1, 2010 at 8:46 Massimo UguesMassimo Ugues 4,4638 gold badges45 silver badges56 bronze badges 2- 2 Soon people will think javascript is a module in jQuery – Anurag Uniyal Commented Apr 1, 2010 at 8:53
- @Massimo Ugues: not as "read", as "answered". If an answer helped you find the solution then to the left of that answer (beneath the vote count) is a tick/check mark outline. If you hover over this, it will turn green and clicking it will mark that answer as the correct one. Now you have over 15 rep, you can also up-vote any answers that helped towards finding a solution. – Andy E Commented Apr 1, 2010 at 9:14
2 Answers
Reset to default 17Apart from object syntax, in JavaScript you can also use an array-like syntax to query object properties. So in your case:
function Animal() { this.id; this.name };
Animal animal = new Animal();
animal.id = "testId";
var propertyName = "id";
alert(animal[propertyName]); // this should alert the value "testId";
Here's an article with more details: http://www.quirksmode.org/js/associative.html
No jQuery needed for this. You need to use square brackets:
animal[propertyName] = "name";