sebasong sebasong - 4 months ago 13
JSON Question

How do I create JavaScript array (JSON format) dynamically?

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
firstName
with variable)? I don't seem to get the nested array right.

Answer
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():

var employees = {
    accounting: []
};

// someData has to be an array
someData.map(function(item) {        
   employees.accounting.push({ 
        "firstName" : item.firstName,
        "lastName"  : item.lastName,
        "age"       : item.age 
    });
}
Comments