up vote 2 down vote favorite

When I have a JavaScript array like this:

var member = {
    "mother": {
        "name" : "Mary",
        "age" : "48"
    },
    "father": {
        "name" : "Bill",
        "age" : "50"
    },
    "brother": {
        "name" : "Alex",
        "age" : "28"
    }
}

How to count objects in this array?!
I mean how to get a counting result 3, because there're only 3 objects inside: mother, father, brother?!

If it's not an array, so how to convert it into JSON array?

flag

possible duplicate of stackoverflow.com/questions/5223/… – Eli Courtwright Apr 22 at 17:29
Someone want to edit it to read object instead of array? – Nerdling Apr 22 at 17:46

4 Answers

up vote 5 down vote accepted

That's not an array, is an object literal, you should iterate over the own properties of the object and count them, e.g.:

function objectLength(obj) {
  var result = 0;
  for(var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
    // or Object.prototype.hasOwnProperty.call(obj, prop)
      result++;
    }
  }
  return result;
}

objectLength(member); // for your example, 3

The hasOwnProperty method should be used to avoid iterating over inherited properties, e.g.

var obj = {};
typeof obj.toString; // "function"
obj.hasOwnProperty('toString'); // false, since it's inherited
link|flag
Might be worth checking for Mozilla's __count__ property before iterating over the object... – J-P Apr 22 at 17:34
2  
@J-P: __count__ is marked as obsolete for Gecko 1.9.3, (in Gecko 1.9.3a5pre, (Firefox 3.7a5pre) it doesn't exist anymore) – CMS Apr 22 at 17:37
@J-P, something that you could check before iterating, is the existence of the new ECMAScript 5th Edition Object.keys method, ES5 is starting to be implemented by all major browser vendors, something like this: if (typeof Object.keys === "function") return Object.keys(obj).length; – CMS Apr 22 at 17:56
up vote 3 down vote

That is not an array, it is an object literal.

You can iterate the objects properties and count how many it owns:

var count = 0;
for (var k in obj) {
  // if the object has this property and it isn't a property
  // further up the prototype chain
  if (obj.hasOwnProperty(k)) count++;
}
link|flag
up vote 0 down vote

Here's how I'd do it

function getObjectLength( obj )
{
  var length = 0;
  for ( var p in obj )
  {
    if ( obj.hasOwnProperty( p ) )
    {
      length++;
    }
  }
  return length;
}
link|flag
up vote 0 down vote

Thats not an array. Its an object literal. An array would look like this

var members = [

    {"mother": {"name" : "Mary", "age" : "48" }},
    {"father": {"name" : "Bill", "age" : "50" }},
    {"brother": {"name" : "Alex", "age" : "28" }}

];
link|flag

Your Answer

get an OpenID
or
never shown

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