6

Possible Duplicate:
How do I create Javascript array(JSON format) dynamically?

I am attempting to 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 out with:

 var employees=new Array();

How do I continue to append to the array dynamically (might change firstName with variable)?

Community
  • 1
  • 1
  • even the description is same... as above duplicate question! – Sudhir Bastakoti Aug 22 '12 at 06:09
  • The fact that you've received 5 upvotes for this question and [9 upvotes on this **identical question**](http://stackoverflow.com/questions/2250953/how-do-i-create-javascript-arrayjson-format-dynamically) is *extremely* suspicious. – user229044 Aug 22 '12 at 13:56

4 Answers4

7
var employees = {accounting: []};

employees.accounting.push({
    "firstName" : "New",
    "lastName"  : "Employee",
    "age"       : 18
});
Lucas Green
  • 3,951
  • 22
  • 27
  • Perfect, thanks! Will accept in a few minutes – Michael Anderson Aug 22 '12 at 06:09
  • On a side note there is good reason so many JavaScripters use array literals besides just their terseness, the variadic signature of new Array() is confusing. – Lucas Green Aug 22 '12 at 06:14
  • https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array Notice that if you pass a single Number it interprets it as a default length for the array, where if you pass two Numbers, it treats it like the first two elements of the array. – Lucas Green Aug 22 '12 at 06:16
  • 1
    _"the variadic signature of new Array() is confusing"_ - And in this case `employees` isn't even supposed to be an array, it's an object... – nnnnnn Aug 22 '12 at 06:20
2
employees.accounting.push({ "firstName" : "New",  // First element
                      "lastName"  : "Person",
                      "age"       : 55 });
George.P
  • 53
  • 4
0
var urNewFirstName='new john';
employees.accounting[0].firstName = urNewFistName;
RAKESH HOLKAR
  • 2,127
  • 5
  • 24
  • 42
0
function Employee(firstName, lastName, age) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.age = age;
}

var employees = {};
employees.accounting = [];
employees.accounting.push(new Employee('John', 'Doe', 23));
employees.accounting.push(new Employee('Mary', 'Smith', 32));
xdazz
  • 158,678
  • 38
  • 247
  • 274