Home > DeveloperSection > Forums > Length of Javascript Object (ie. Associative Array)
Tanuj Kumar

Total Post:134

Posted on    February-14-2013 2:11 AM

 JavaScript JavaScript 

 1 Reply(s)
 1079  View(s)
Rate this:


If I have a JavaScript associative array say:

var myArray = new Object();
myArray["firstname"] = "Gareth";
myArray["lastname"] = "Simpson";
myArray["age"] = 21;

Is there a built in or accepted best practice way to get the length of this array?

EDIT: JavaScript does not have associative arrays -- it only has objects.

Please help me!

Thanks in advance!


Total Post:604

Posted on    February-16-2013 3:58 AM

Hi Tanuj!

Get the length of JavaScript Object, try this way

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    return size;

// Get the size of an object
var size = Object.size(myArray);

Don't want to miss updates? Please click the below button!

Follow MindStick