151

我有这个 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;  });
}
4

4 回答 4

180

这就是你需要的!

function onGeneratedRow(columnsResult)
{
    var jsonData = {};
    columnsResult.forEach(function(column) 
    {
        var columnName = column.metadata.colName;
        jsonData[columnName] = column.value;
    });
    viewData.employees.push(jsonData);
 }
于 2013-05-12T12:15:31.137 回答
122

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

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

于 2013-05-12T12:32:04.363 回答
17

这个话题,尤其是 Xotic750 的回答对我很有帮助。我想生成一个 json 变量以使用 ajax 将其传递给 php 脚本。我的值存储在两个数组中,我希望它们为 json 格式。这是一个通用示例:

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

控制台日志中的结果应该是这样的:

{
   "objArray1": {
        "obj1": 121,
        "obj2": 324,
        "obj3": 42,
        "obj4": 31
   },
   "objArray2": {
        "obj1": 232,
        "obj2": 131,
        "obj3": 443
  }
}
于 2014-05-24T21:17:11.153 回答
2

JavaScript

var myObj = {
   id: "c001",
   name: "Hello Test"
}

结果(JSON)

{
   "id": "c001",
   "name": "Hello Test"
}
于 2019-02-04T06:25:12.857 回答