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

时间:2013-05-12 12:11:26

标签: javascript json

我有这个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 个答案:

答案 0 :(得分:125)

这就是你所需要的!

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

答案 1 :(得分:76)

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

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

答案 2 :(得分:8)

本主题,尤其是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
  }
}

答案 3 :(得分:-1)

  

JavaScript

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

Result(JSON)

{
   "id": "c001",
   "name": "Hello Test"
}