Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamic call property on javascript object with jQuery

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

like image 415
Massimo Ugues Avatar asked Apr 01 '10 08:04

Massimo Ugues


People also ask

Can we add dynamically named properties to JavaScript object?

In JavaScript, you can choose dynamic values or variable names and object names and choose to edit the variable name in the future without accessing the array. To do, so you can create a variable and assign it a particular value.


1 Answers

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

like image 100
Slavo Avatar answered Oct 04 '22 17:10

Slavo