3

I need get js object properties count.

I search and found solutions like this:

var foo = {"key1": "value1", "key2": "value2", "key3": "value3"};
var count = 0;
for (var k in foo) {
    if (foo.hasOwnProperty(k)) {
      ++count;
    }
}

Question: why needed condition if (foo.hasOwnProperty(k)) { ?

I think that this code must work good always, without this condition also.

I am wrong?

Oto Shavadze
  • 34,391
  • 48
  • 116
  • 201

3 Answers3

3

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

yes, the hasOwnProperty method is really reduntant here.

Anyway, why you need to get properties count? I'm afraid you are solving something a bad way.

Community
  • 1
  • 1
amik
  • 4,606
  • 2
  • 27
  • 54
  • Not really redundant if you want to avoid counting inherited members. Hopefully no one is adding members to `Object.prototype` but it does happen (including in an older version of a popular JavaScript framework). – Tim Goodman Feb 25 '13 at 14:28
  • @user1660584 `Anyway, why you need to get properties count? I'm afraid you are solving something a bad way.` --- I am obtain associative array from php to js and I need get this array count in js. Thank you, thanks everyone – Oto Shavadze Feb 25 '13 at 14:44
2

Some objects have properties added by the system (ie prototype).

You normally don't want to count those. The condition you ask about will make sure you only count properties belonging to your object itself.

So if you intend to make a function that will return the count for any object, its probably better to include the condition, otherwise you don't necessarily need to.

Tim De Lange
  • 731
  • 3
  • 6
1

It's to prevent you from counting inherited members.

If you do this (not advisable):

Object.prototype.x = 1;

Then this gives a count of 4:

var foo = {"key1": "value1", "key2": "value2", "key3": "value3"};
var count = 0;
for (var k in foo) {
  ++count;
} 

But with if (foo.hasOwnProperty(k)) it still gives 3.

Tim Goodman
  • 20,835
  • 7
  • 54
  • 80