Find Number of Properties in a JavaScript Object

Use the Object.keys() method, passing the object you want to inspect, to get an array of all the (own) enumerable properties of the object.

Example - Using Object.keys() method

Let's demonstrates how to calculate how many properties has a JavaScript object using Object.keys() method.
 // using Object Literals
 var user = {
    firstName : 'Ramesh',
    lastName : 'Fadatare',
    emailId : '[email protected]',
    age : 29,
    getFullName : function (){
        return user.firstName + " " + user.lastName;
    }
}

function testNumberOfProperties(){
    let count = Object.keys(user).length;
    console.log("Number of properties in User object is : " + count);
}

testNumberOfProperties();
Output:
Number of properties in User object is : 5
For the best learning experience, I highly recommended that you open a console (which, in Chrome and Firefox, can be done by pressing Ctrl+Shift+I), navigate to the "console" tab, copy-and-paste each JavaScript code example from this guide, and run it by pressing the Enter/Return key.
You can refer below screenshot for your testing:

Comments