WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES
Advertisements

How to Get the Length of a JavaScript Object

Topic: JavaScript / jQueryPrev|Next

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

Related FAQ

Here are some more FAQ related to this topic:

Advertisements
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties