I’m working with a JavaScript object and I’m curious about the recommended methods or built-in functions to find out how many properties it contains. For example, I have the following object:
const user = new Object();
user[‘firstName’] = ‘John’;
user[‘lastName’] = ‘Doe’;
user[‘age’] = 30;
What is the best way to achieve this?
To find out the number of properties in a JavaScript object, you can use Object.keys()
. It returns an array of the object's own property names. Simply get the length of this array to determine the size:
const size = Object.keys(user).length;
console.log(size); // Outputs: 3
This method is efficient and works well in most scenarios. Keep it simple!