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