Create JSON object dynamically via JavaScript (Without concate strings)
This is what you need!
function onGeneratedRow(columnsResult)
{
var jsonData = {};
columnsResult.forEach(function(column)
{
var columnName = column.metadata.colName;
jsonData[columnName] = column.value;
});
viewData.employees.push(jsonData);
}
Perhaps this information will help you.
var sitePersonel = {};
var employees = []
sitePersonel.employees = employees;
console.log(sitePersonel);
var firstName = "John";
var lastName = "Smith";
var employee = {
"firstName": firstName,
"lastName": lastName
}
sitePersonel.employees.push(employee);
console.log(sitePersonel);
var manager = "Jane Doe";
sitePersonel.employees[0].manager = manager;
console.log(sitePersonel);
console.log(JSON.stringify(sitePersonel));
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
}
}