Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create a json object in javascript for loop [closed]

I would like to create a JSON object inside a for loop using javascript. I am expecting an result something like this:

{
   "array":[
      {
         "value1":"value",
         "value2":"value"
      },
      {
         "value1":"value",
         "value2":"value"
      }
   ]
}

Can somebody help me on how to achieve this result in javascript ?

like image 334
Gopi Nath Avatar asked Apr 15 '15 19:04

Gopi Nath


1 Answers

Instead of creating the JSON in the for-loop, create a regular JavaScript object using your for-loops and use JSON.stringify(myObject) to create the JSON.

var myObject = {};

for(...) {
   myObject.property = 'newValue';
   myObject.anotherProp = [];
   for(...) {
       myObject.anotherProp.push('somethingElse');
    }
}

var json = JSON.stringify(myObject);
like image 180
S Farron Avatar answered Oct 10 '22 00:10

S Farron