How do I create JavaScript array (JSON format) dynamically?
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;
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
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:
var employees = {
accounting: []
};
someData.map(function(item) {
employees.accounting.push({
"firstName" : item.firstName,
"lastName" : item.lastName,
"age" : item.age
});
}
var student = [];
var obj = {
'first_name': name,
'last_name': name,
'age': age,
}
student.push(obj);