Q:

How to Get the Length of a JavaScript Object

0

How to Get the Length of a JavaScript Object

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the Object.keys() Method

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:

// Sample object
var myObj = {
    make: "Ferrari",
    model: "Portofino",
    fuel: "Petrol",
    year: 2018
};

// Getting object length
var size = Object.keys(myObj).length;
console.log(size); // Prints: 4

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Check If an Element Contains a Class in Jav... >>
<< How to Merge the Properties of Two JavaScript Obje...