Back
How do I create a JavaScript array dynamically?
Consider the array of objects:
var someData = [ {firstName: "Max", lastName: "Mustermann", age: 40}, {firstName: "Hagbard", lastName: "Celine", age: 44}, {firstName: "Karl", lastName: "Koch", age: 42},];
var someData = [
{firstName: "Max", lastName: "Mustermann", age: 40},
{firstName: "Hagbard", lastName: "Celine", age: 44},
{firstName: "Karl", lastName: "Koch", age: 42},
];
Using 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 });}
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 by using Array.prototype.map():
var employees = { accounting: []};someData.map(function(item) { employees.accounting.push({ "firstName" : item.firstName, "lastName" : item.lastName, "age" : item.age });}
someData.map(function(item) {
31k questions
32.8k answers
501 comments
693 users