6

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 ?

Gopi Nath
  • 413
  • 3
  • 7
  • 21
  • 2
    Just use normal objects to create the structure and use `JSON.stringify` at the end to convert it to JSON. Don't build JSON manually. – Felix Kling Apr 15 '15 at 19:26
  • possible duplicate of [Safely turning a JSON string into an object](http://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object) – Celeo Apr 15 '15 at 19:57

3 Answers3

18

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);
S Farron
  • 561
  • 1
  • 5
  • 10
  • What would be the equivalent code in typescript? In typescript I get the error `error TS2339: Property 'someproperty' does not exist on type '{}'.` – ontherocks Jul 14 '21 at 02:58
3
var loop = [];

for(var x = 0; x < 10; x++){
 loop.push({value1: "value_a_" + x , value2: "value_b_" + x});
}

JSON.stringify({array: loop});
000
  • 26,951
  • 10
  • 71
  • 101
QBM5
  • 2,778
  • 2
  • 17
  • 24
1

This code produces what you need:

var result = {"array": []};


for(var i = 0; i < 2; i++){
    var valueDict = {};
    for(var j = 0; j < 2; j++){
        valueDict["value" + (j+1).toString()] = "value";
    }
    result["array"].push(valueDict);
}

It uses the push function to add items to the list, and the indexer [] notation notation to modify the entries on the object prototype.

Hope it helps,

avenet
  • 2,894
  • 1
  • 19
  • 26