Finding the length of a JavaScript object


Suppose we have an object like this −

const obj = {
   name: "Ramesh",
   age: 34,
   occupation: "HR Manager",
   address: "Tilak Nagar, New Delhi",
   experience: 13
};

We are required to write a JavaScript function on Objects that computes their size (i.e., the number of properties in it).

Example

Following is the code −

const obj = {
   name: "Ramesh",
   age: 34,
   occupation: "HR Manager",
   address: "Tilak Nagar, New Delhi",
   experience: 13
};
Object.prototype.size = function(obj) {
   let size = 0, key;
   for (key in obj) {
      if (obj.hasOwnProperty(key)){
         size++
      };
   };
   return size;
};
const size = Object.size(obj);
console.log(size);

This will produce the following output on console −

5

Updated on: 01-Oct-2020

122 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements