views:

81

answers:

2

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

+1  A: 

No jQuery needed for this. You need to use square brackets:

animal[propertyName] = "name";
Andy E
A: 

Apart from object syntax, in JavaScript you can also use an array-like syntax to query object properties. So in you 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

Slavo