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 ?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With