This topic, especially the answer of Xotic750 was very helpful to me. I wanted to generate a json variable to pass it to a php script using ajax. My values were stored into two arrays, and i wanted them in json format. This is a generic example:
valArray1 = [121, 324, 42, 31];
valArray2 = [232, 131, 443];
myJson = {objArray1: {}, objArray2: {}};
for (var k = 1; k < valArray1.length; k++) {
var objName = 'obj' + k;
var objValue = valArray1[k];
myJson.objArray1[objName] = objValue;
}
for (var k = 1; k < valArray2.length; k++) {
var objName = 'obj' + k;
var objValue = valArray2[k];
myJson.objArray2[objName] = objValue;
}
console.log(JSON.stringify(myJson));
The result in the console Log should be something like this:
{
"objArray1": {
"obj1": 121,
"obj2": 324,
"obj3": 42,
"obj4": 31
},
"objArray2": {
"obj1": 232,
"obj2": 131,
"obj3": 443
}
}