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

2022-08-30 04:14:19

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

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


答案 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 
    });
}

答案 2
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;