How can i find the total number of keys if the Object is inside an array [duplicate]
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 Object
s 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.
精彩评论