Skip to content Skip to sidebar Skip to footer

How To Count Javascript Array Objects?

When I have a JavaScript object like this: var member = { 'mother': { 'name' : 'Mary', 'age' : '48' }, 'father': { 'name' : 'Bill', 'age

Solution 1:

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

functionobjectLength(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

Solution 2:

You can try this code, it works perfectly in a browser:

Object.keys(member).length;

Solution 3:

If you are using jquery on your page, this will work:

$(member).toArray().length;

Solution 4:

You can use the Object.keys() method that returns an array of a given object's own enumerable properties:

Object.keys(member).length;

Solution 5:

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 chainif (obj.hasOwnProperty(k)) count++;
}

Post a Comment for "How To Count Javascript Array Objects?"