Computer >> Computer tutorials >  >> Programming >> Javascript

Best way to find length of JSON object in JavaScript


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

The code for this will be −

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);

Output

The output in the console will be −

5