8

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

2
  • 2
    Soon people will think javascript is a module in jQuery 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. Commented Apr 1, 2010 at 9:14

2 Answers 2

17

Apart 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

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

Comments

3

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

animal[propertyName] = "name";

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.