Skip to content
the poor coder

object length javascript

Poor Man
Published
Reading time
1 min read

Object Length in JavaScript#

If you are working with JavaScript and need to find the number of properties in an object, you can use the Object.keys() method to get an array of the object's keys, and then use the length property of that array to get the number of keys:

Text

    const myObj = { 
        name: "Raju", 
        age: 25, 
        location: "India" 
    };
    
    const numOfKeys = Object.keys(myObj).length;
    console.log(numOfKeys); // output: 3

The above code creates an object myObj with three properties - name, age, and location. The Object.keys(myObj) method returns an array of keys - ["name", "age", "location"], and the .length property of that array gives the number of keys, which is 3 in this case.

Another way to get the number of properties in an object is to loop through the object and count the number of properties:

Text

    let count = 0;
    for(let prop in myObj) {
        if(myObj.hasOwnProperty(prop)) {
            count++;
        }
    }
    console.log(count); // output: 3

In the above code, we first initialize a variable count to 0. Then we loop through the properties of the object using a for...in loop. For each property, we check if the property belongs to the object itself (and not to its prototype) using the hasOwnProperty() method. If it does, we increment the count variable. Finally, we log the value of count, which gives us the number of properties in the object.

So, these are the two ways you can find the number of properties in an object in JavaScript.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC