2

Possible Duplicate:
How to efficiently count the number of keys/properties of an object in JavaScript?

var array = [{key:value,key:value}]

How can i find the total number of keys if it's an array of Object. When i do check the length of the array, it gives me one.

Community
  • 1
  • 1
John Cooper
  • 6,277
  • 26
  • 72
  • 97

2 Answers2

2

If you want to know the number of unique properties of Objects in an Array, this should do it...

var uniqueProperties = [];

for (var i = 0, length = arr.length; i < length; i++) {
   for (var prop in arr[i]) {
       if (arr[i].hasOwnProperty(prop) 
           && uniqueProperties.indexOf(prop) === -1
          ) {
          uniqueProperties.push(prop);
       }
   } 
}

var uniquePropertiesLength = uniqueProperties.length;

jsFiddle.

Note that an Array's indexOf() doesn't have the best browser support. You can always augment the Array prototype (though for safety I'd make it part of a util object or similar).

alex
  • 438,662
  • 188
  • 837
  • 957
  • What does this mean uniqueProperties.indexOf(propertyName) === -1 – John Cooper Jul 17 '11 at 13:05
  • @JohnCooper: It checks to see if the property name already exists in the `uniqueProperties` `Array`. Be sure to check the footnote about browser compatibility. – alex Jul 17 '11 at 13:08
0

If the array will only have one object, array[0] represents the object.

If there's more than one object, you'll need to decide what exactly you want to count.

BoltClock
  • 630,065
  • 150
  • 1,295
  • 1,284