Adding key:value pair to JSON using javascript -


this question has answer here:

i have object following

var data={title: "italy"} 

i want t check few conditions , add data whoch met condoitions :

if(condition1)      //output data={title: "italy",id1: somecaluatedvalue} if(condition2)      /*output data={title: "italy",id1: somecaluatedvalue,id2: somevalue}        if condition1 true or data={title: "italy",id1=2: somecaluatedvalue} if        condition1 false */ 

it continue in way inside loop. how can in javascript?

i have json

no don't, have object literal.

to set properties on javascript object can this:

data.id1 = somevalue; 

or this:

data["id1"] = somevalue; 

the second particularly useful when need dynamically generate property name, seems alluding to. this:

for (var i=0; < arrayofconditions.length; i++) {     if (arrayofconditions[i]) {         data["id" + i] = somevalue;     } } 

and if do need json @ end, can do:

var myjson = json.stringify(data); 

Comments