我有以下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; }); }
这就是您所需要的!
function onGeneratedRow(columnsResult) { var jsonData = {}; columnsResult.forEach(function(column) { var columnName = column.metadata.colName; jsonData[columnName] = column.value; }); viewData.employees.push(jsonData); }