As a dynamic call property in a javascript object using jQuery

Hello everybody. I got a javascript object with some hints let's say

function Animal() { this.id; this.name; 

I need to call the id function dynamically in order 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 this? With jQuery?

respectfully

Massimo

+4
source share
2 answers

In addition to object syntax, in JavaScript you can also use array type 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

+12
source

This does not require jQuery. You need to use square brackets:

 animal[propertyName] = "name"; 
+2
source

Source: https://habr.com/ru/post/1305740/


All Articles