Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

Thanks.

share|improve this question
6  
The preferred way of creating a array in javascript is var employess = []; not var employees=new Array(); –  Mattias Jakobsson Feb 12 '10 at 10:08

2 Answers 2

up vote 75 down vote accepted
var employees = {
    accounting: []
};

for(var i in someData) {

    var item = someData[i];

    employees.accounting.push({ 
        "firstName" : item.firstName,
        "lastName"  : item.lastName,
        "age"       : item.age 
    });
}
share|improve this answer
    
Uncaught TypeError: Cannot call method 'push' of undefined –  Poonam Bhatt Jan 9 at 7:34
    
thanks found my error –  Poonam Bhatt Jan 9 at 7:41
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;
share|improve this answer
    
this is better than the above example, this also tells how to add the array dynamically. –  Harry Jul 30 at 4:49

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.