如何动态创建 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) ?我好像没有把嵌套数组搞对。

363768 次浏览

我们的物体数组

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

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

这是我的工作!

我希望它能对其他人有用!

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