开发者

How can i find the total number of keys if the Object is inside an array [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How to efficiently c开发者_如何转开发ount 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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜