Languages
[Edit]
EN

JavaScript - how to get object length

3 points
Created by:
Giles-Whittaker
319

In this article, we would like to show you how to get object length in JavaScript.

Below examples show two ways how to do that:

  1. Using Object.keys() method,
  2. Using hasOwnProperty() method.

1. Object.keys() method example

In this solution we use:

  • ¬†Object.keys() method which¬†returns an array of the¬†given object's own enumerable property¬†names.
  • .length property to check¬†the number of elements in that array.

Runnable example:

// ONLINE-RUNNER:browser;

var object = { 'a':1,'b':2,'c':3 }
console.log(Object.keys(object).length); // 3

2. hasOwnProperty() method example 

In this solution, we loop through the object properties checking whether the object has the specified property as its own with hasOwnProperty() method and we increase the counter for every existing property.

// ONLINE-RUNNER:browser;

var object = { 'a':1,'b':2,'c':3 }

var counter = 0;
for (var i in object) {
    if (object.hasOwnProperty(i)) {
        counter++;
    }
}
console.log(counter); // 3

References

Native Advertising
ūüöÄ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

‚̧ԳŹūüíĽ ūüôā

Join