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.

6
  • @Darin Dimitrov: Its an array of objects... not a plain object.. Commented Jul 17, 2011 at 12:44
  • @Darin Dimitrov: His previous question is a dupe of that, this one asks something a little different. Not sure if it should've been a separate question, but I guess he didn't get responses from the earlier post. Commented Jul 17, 2011 at 12:45
  • It is right - there is one object in the array. The question needs some polishing... Are you trying to get the total number of keys from the object in the array? Or something else? Commented Jul 17, 2011 at 12:46
  • @John Cooper, well then apply the technique in the dupe to array[0] which is a single object. Commented Jul 17, 2011 at 12:46
  • @Nicolae Albu: Yes i am trying to get the total number of keys from the object in an array Commented Jul 17, 2011 at 12:48

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

2 Comments

What does this mean uniqueProperties.indexOf(propertyName) === -1
@JohnCooper: It checks to see if the property name already exists in the uniqueProperties Array. Be sure to check the footnote about browser compatibility.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.