如何动态创建 JavaScript 数组(JSON 格式)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2250953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I create JavaScript array (JSON format) dynamically?
提问by sebas23
I am trying the create the following:
我正在尝试创建以下内容:
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
I started with
我开始了
var employees = new Array();
How do I continue to create the array dynamically (might change firstNamewith variable)? I don't seem to get the nested array right.
如何继续动态创建数组(可能会firstName随变量变化)?我似乎没有得到正确的嵌套数组。
回答by Alex
Our array of objects
我们的对象数组
var someData = [
{firstName: "Max", lastName: "Mustermann", age: 40},
{firstName: "Hagbard", lastName: "Celine", age: 44},
{firstName: "Karl", lastName: "Koch", age: 42},
];
with for...in
与 for...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
});
}
or with Array.prototype.map(), which is much cleaner:
或使用Array.prototype.map(),这更干净:
var employees = {
accounting: []
};
someData.map(function(item) {
employees.accounting.push({
"firstName" : item.firstName,
"lastName" : item.lastName,
"age" : item.age
});
}
回答by Chase
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;
回答by alexventuraio
What I do is something just a little bit different from @Chase answer:
我所做的与@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
});
}
And that work form me!
那工作形成了我!
I hope it could be useful for some body else!
我希望它对其他人有用!
回答by Venu Upadhyay
var student = [];
var obj = {
'first_name': name,
'last_name': name,
'age': age,
}
student.push(obj);

