Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
42
rated 0 times [  47] [ 5]  / answers: 1 / hits: 109138  / 14 Years ago, thu, april 22, 2010, 12:00:00

When I have a JavaScript object like this:



var member = {
mother: {
name : Mary,
age : 48
},
father: {
name : Bill,
age : 50
},
brother: {
name : Alex,
age : 28
}
}


How to count objects in this object?!

I mean how to get a counting result 3, because there're only 3 objects inside: mother, father, brother?!



If it's not an array, so how to convert it into JSON array?


More From » oop

 Answers
59

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



function objectLength(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

[#97001] Tuesday, April 20, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ronans

Total Points: 460
Total Questions: 109
Total Answers: 108

Location: Slovenia
Member since Sat, Sep 11, 2021
3 Years ago
;