How to create json object in javascript for loop

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

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

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

+5
source share
3 answers

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

 var myObject = {}; for(...) { myObject.property = 'newValue'; myObject.anotherProp = []; for(...) { myObject.anotherProp.push('somethingElse'); } } var json = JSON.stringify(myObject); 
+11
source
 var loop = []; for(var x = 0; x < 10; x++){ loop.push({value1: "value_a_" + x , value2: "value_b_" + x}); } JSON.stringify({array: loop}); 
+1
source

This code creates 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 indexer [] notation to change the entries in the prototype object.

Hope this helps,

0
source

All Articles