Crear objetos JSON dinámicamente a través de JavaScript (Sin cadenas concate)


Tengo estos datos JSON:

{
    "employees": [
        {
            "firstName": "John",
            "lastName": "Doe"
        },
        {
            "firstName": "Anna",
            "lastName": "Smith"
        },
        {
            "firstName": "Peter",
            "lastName": "Jones"
        }
    ]
}

Supongamos que no conozco cuántas columnas y filas de empleados tengo, ¿cómo puedo crear este objeto en JavaScript (Sin cadenas concate)? Supongamos que obtengo cada fila en el método "onGeneratedRow", y necesito empujar cada columna (FirstName, LastName) a los corchetes' {}'.

var viewData = { 
    employees : [] 
};

var rowNum = -1; 

function onGeneratedRow(columnsResult)
{
    rowNum = rowNum + 1;
    viewData.employees.push({});    
    columnsResult.forEach(function(column) {                  
    var columnName = column.metadata.colName;
    viewData.employees[rowNum][columnName] = column.value;  });
}
Author: Waqar Alamgir, 2013-05-12

3 answers

Esto es lo que necesitas!

function onGeneratedRow(columnsResult)
{
    var jsonData = {};
    columnsResult.forEach(function(column) 
    {
        var columnName = column.metadata.colName;
        jsonData[columnName] = column.value;
    });
    viewData.employees.push(jsonData);
 }
 116
Author: Waqar Alamgir,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-12 12:28:10

Tal vez esta información le ayude.

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));
 65
Author: Xotic750,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-15 04:13:37

Este tema, especialmente la respuesta de Xotic750 fue muy útil para mí. Quería generar una variable json para pasarla a un script php usando ajax. Mis valores se almacenaron en dos matrices, y los quería en formato json. Este es un ejemplo genérico:

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));

El resultado en el registro de consola debería ser algo como esto:

{
   "objArray1": {
        "obj1": 121,
        "obj2": 324,
        "obj3": 42,
        "obj4": 31
   },
   "objArray2": {
        "obj1": 232,
        "obj2": 131,
        "obj3": 443
  }
}
 8
Author: the_butterfly_effect,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-17 11:31:49