Javascript size of object 

In JavaScript, almost everything is an object. Objects are used to store information in key-value pairs, where the value can be any other data type or function. Unlike arrays and strings, objects do not have a predefined property that returns their length. Therefore, if you try to get the value of an object’s length property,…

In JavaScript, almost everything is an object. Objects are used to store information in key-value pairs, where the value can be any other data type or function. Unlike arrays and strings, objects do not have a predefined property that returns their length.

Therefore, if you try to get the value of an object’s length property, it returns undefined. Here are, for example, three Javascript ways to get the length of an object, let’s call it myObj.

const myObj = {
key1: 'val1',
key2: 'val2',
key3: 'val3',
key4: 'val4',
};


Object.keys()


The Object.keys() method returns an array of key names, then you can read its length property and get the length of the object.

console.log(Object.keys(myObj).length); // 4


Cycle for..in


You can get the length of the object by going through all its properties in a loop.

let count = 0;
for (let key in myObj) {
count++;
}
console.log(count); // 4


Adding the length property to Object.prototype


Adding the length property to the object prototype allows it to be used repeatedly throughout the application.

if (!Object.prototype.length) {
Object.defineProperty(Object.prototype, 'length', {
get: function() {
return Object.keys(this).length;
}
});
}


The advantages of the latter option are quite obvious: define and use the property once from anywhere in the application, no loop to enumerate and count the keys of the object.

Similar Posts

Leave a Reply

Your email address will not be published.