javascript get number of elements in object


// Get the length of an object with JavaScript
// Method 1 - using Object.keys()
// Object.keys() returns an array of the object's own enumerable properties
let myObject = {
    a: 1,
    b: 2,
    c: 3
};

let numProperties = Object.keys(myObject).length;
console.log(numProperties); // 3

// Method 2 - using a for..in loop
// Iterates over all enumerable properties of an object and its prototype chain
let myObject = {
    a: 1,
    b: 2,
    c: 3
};

let count = 0;

for(let key in myObject) {
    if(myObject.hasOwnProperty(key)) {
        count++;
    }
}

console.log(count); // 3
    

Using the above two methods, you can easily determine the number of elements in an object in JavaScript. The first method is using the Object.keys() method which returns an array of the object's own enumerable properties. It is important to note that the Object.keys() method does not include inherited properties. The second method is using a for..in loop. This approach iterates over all enumerable properties of an object and its prototype chain. When using this approach, it is important to use the hasOwnProperty() method to make sure that only properties belonging to the object itself are considered and not properties belonging to its prototype chain.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe