You can simply use the Object.keys() method along with the length property to get the length of a JavaScript object. The Object.keys() method returns an array of a given object's own enumerable property names, and the length property returns the number of elements in that array.
Let's take a look at an example to understand how it basically works:
Tip: Enumerable properties are those properties that will show up if you iterate over the object using for..in loop or Object.keys() method. All the properties created via simple assignment or via a property initializer are enumerable by default.
Here's another example demonstrating how get the length of any object in JavaScript.
// Creating an object
var myObj = new Object();
// Adding properties
myObj["name"] = "Peter";
myObj["age"] = 24;
myObj["gender"] = "Male";
// Printing object in console
console.log(myObj);
// Prints: {name: "Peter", age: 24, gender: "Male"}
// Getting object length
var size = Object.keys(myObj).length;
console.log(size); // Prints: 3
Use the
Object.keys()MethodYou can simply use the
Object.keys()method along with thelengthproperty to get the length of a JavaScript object. TheObject.keys()method returns an array of a given object's own enumerable property names, and thelengthproperty returns the number of elements in that array.Let's take a look at an example to understand how it basically works:
Tip: Enumerable properties are those properties that will show up if you iterate over the object using
for..inloop orObject.keys()method. All the properties created via simple assignment or via a property initializer are enumerable by default.Here's another example demonstrating how get the length of any object in JavaScript.
need an explanation for this answer? contact us directly to get an explanation for this answer