0

I have an Object initially like the following

var data={title: "Italy"}

I want t check few conditions and then add to the data whoch met the condoitions :

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

It will continue in this way inside a loop. How can i do this in javascript?

Md Johirul Islam
  • 5,042
  • 4
  • 23
  • 56

1 Answers1

2

I have a JSON

No you don't, you have an object literal.

To set properties on a Javascript object you can do this:

data.id1 = somevalue;

or this:

data["id1"] = somevalue;

The second is particularly useful when you need to dynamically generate property name, which seems to something you are alluding to. So you could do something like this:

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

And if you do need JSON at the end, you can just do:

var myJson = JSON.stringify(data);
Matt Burland
  • 44,552
  • 18
  • 99
  • 171