[javascript] 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.

This question is related to javascript json

The answer is


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;

What I do is something just a little bit different from @Chase answer:

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!


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