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)?

2
  • even the description is same... as above duplicate question! Commented Aug 22, 2012 at 6:09
  • The fact that you've received 5 upvotes for this question and 9 upvotes on this identical question is extremely suspicious. Commented Aug 22, 2012 at 13:56

4 Answers 4

7
var employees = {accounting: []};

employees.accounting.push({
    "firstName" : "New",
    "lastName"  : "Employee",
    "age"       : 18
});
Sign up to request clarification or add additional context in comments.

4 Comments

Perfect, thanks! Will accept in a few minutes
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.
developer.mozilla.org/en-US/docs/JavaScript/Reference/… 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.
"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...
2
employees.accounting.push({ "firstName" : "New",  // First element
                      "lastName"  : "Person",
                      "age"       : 55 });

Comments

0
var urNewFirstName='new john';
employees.accounting[0].firstName = urNewFistName;

Comments

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));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.