Skip to content Skip to sidebar Skip to footer

Is It Possiblle To Add Dynamic Field Name In The Javascript Object?

I am trying to add the dynamic field name and update the value according to that.in my case eventType is of 4 types delivery, send, open, click.and when i am trying to use this cod

Solution 1:

Dynamic keys can be added to the JSON object.

Example :

var key = 'age'var keys = ['name','gender'];
vardata = {};

Now here is a catch if you want to decide the key on runtime you need to use [], because it allows the expression to evaluate i.e.

data[keys[0]] = 'Rohan'//keys[0] will interpreted to name during the execution//data ==>> {name:'Rohan'}

whereas

data.key = '19'//"key" will be treated as an individual entity i.e. as a valid key name//data ==>> {key:'19'}//whereasdata[key] = '19'//results in data ==>> {age:'19'}

And also note that if you wrap a double "" inside [] it will also be treated as an individual entity

data['key'] = '19'// data ==>> {key:'19'}

Post a Comment for "Is It Possiblle To Add Dynamic Field Name In The Javascript Object?"