如何动态创建JavaScript数组(JSON格式)?

时间:2010-02-12 10:02:18

标签: javascript json

我正在尝试创建以下内容:

var employees = {"accounting": [   // accounting is an array in employees.
                    { "firstName" : "John",  // First element
                      "lastName"  : "Doe",
                      "age"       : 23 },

                    { "firstName" : "Mary",  // Second Element
                      "lastName"  : "Smith",
                      "age"       : 32 }
                  ] // End "accounting" array.                                  

    } // End Employees

我从

开始
 var employees = new Array();

如何动态继续创建数组(可能会使用变量更改firstName)?我似乎没有得到嵌套数组。

4 个答案:

答案 0 :(得分:233)

我们的对象数组

var someData = [
   {firstName: "Max", lastName: "Mustermann", age: 40},
   {firstName: "Hagbard", lastName: "Celine", age: 44},
   {firstName: "Karl", lastName: "Koch", age: 42},
];

with ... in

var employees = {
    accounting: []
};

for(var i in someData) {    

    var item = someData[i];   

    employees.accounting.push({ 
        "firstName" : item.firstName,
        "lastName"  : item.lastName,
        "age"       : item.age 
    });
}

Array.prototype.map(),更清洁:

var employees = {
    accounting: []
};

someData.map(function(item) {        
   employees.accounting.push({ 
        "firstName" : item.firstName,
        "lastName"  : item.lastName,
        "age"       : item.age 
    });
}

答案 1 :(得分:34)

var accounting = [];
var employees = {};

for(var i in someData) {

    var item = someData[i];

   accounting.push({ 
        "firstName" : item.firstName,
        "lastName"  : item.lastName,
        "age"       : item.age 
    });
}

employees.accounting = accounting;

答案 2 :(得分:4)

我所做的事与@Chase回答有点不同:

var employees = {};

// ...and then:
employees.accounting = new Array();

for (var i = 0; i < someArray.length; i++) {
    var temp_item = someArray[i];

    // Maybe, here make something like:
    // temp_item.name = 'some value'

    employees.accounting.push({
        "firstName" : temp_item.firstName,
        "lastName"  : temp_item.lastName,
        "age"       : temp_item.age
    });
}

这项工作形成了我!

我希望它对其他人有用!

答案 3 :(得分:2)

var student = [];
var obj = {
    'first_name': name,
    'last_name': name,
    'age': age,
}
student.push(obj);