通过 JavaScript 动态创建 JSON 对象(不带连接字符串)

2022-08-30 02:39:46

我有这个JSON数据:

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

假设我不知道我有多少列和行的员工,我如何在JavaScript中创建这个对象(没有连接字符串)?假设我在“onGeneratedRow”方法中获取每一行,并且我需要将每列(firstName,lastName)推送到“{}”括号中。

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

答案 1

这就是你需要的!

function onGeneratedRow(columnsResult)
{
    var jsonData = {};
    columnsResult.forEach(function(column) 
    {
        var columnName = column.metadata.colName;
        jsonData[columnName] = column.value;
    });
    viewData.employees.push(jsonData);
 }

答案 2

也许这些信息会对你有所帮助。

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