小编典典

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

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随变量更改)?我似乎没有正确的嵌套数组。


阅读 307

收藏
2020-07-27

共1个答案

小编典典

我们的对象数组

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

与…有关

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 
    });
}
2020-07-27