Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get items quantity in js object [duplicate]

Tags:

javascript

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?

like image 436
Oto Shavadze Avatar asked Sep 02 '26 00:09

Oto Shavadze


2 Answers

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.

like image 197
amik Avatar answered Sep 03 '26 13:09

amik


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.

like image 29
Tim De Lange Avatar answered Sep 03 '26 12:09

Tim De Lange



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!