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


122

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

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


8
在javascript中创建数组的首选方法是var employeeess = []; 不是var employee = new Array();
Mattias Jakobsson

Answers:


254

我们的对象数组

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

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

这比上面的示例更好,这也告诉了如何动态添加数组。
哈利

但是,如果我将其传递到另一个文件中,则它是未定义的。
Tripathi29'2015-2-16

如果我需要该数组的名称是动态的怎么办?
easythrees

5

我所做的只是与@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
    });
}

那就是我的工作!

我希望它对其他身体可能有用!


可变项来自何处?
Irfan Raza

现在固定的@IrfanRaza
alexventuraio

5
var student = [];
var obj = {
    'first_name': name,
    'last_name': name,
    'age': age,
}
student.push(obj);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.