DEV Community

Mohamed Ibrahim
Mohamed Ibrahim

Posted on β€’ Edited on β€’ Originally published at mo-ibra.com

2

How to get the length of object in JavaScript

In this article we will learn how to get length of an object.

It is very common to get length of an object in JavaScript.


Problem

Now we have a problem, which is that we want to know the length of the object.

Let's imagine we have an object like this:

const myObject = {
    name: "John",
    age: 30,
    isMarried: true,
    country: "USA"
};

console.log(myObject);
// { name: 'John', age: 30, isMarried: true, country: 'USA' }
Enter fullscreen mode Exit fullscreen mode

And we want to get length of that object!

How to solve this problem?

Now let's ask a question, is there a built-in function as in the array that returns the length of the object? The answer is no.

OK, but how do we know the length?

We can take advantage of the function in the array, but now we have to convert the object into an array first.

So we will use Object.keys() because it returns an array with all keys.

The solution will be as follows:

  • We will convert our object to an array
  • We will use Object.keys() because it returns an array with all keys.
  • Use the length property to get the number of elements in that array

Solution: Get length of an object

// Object
const myObject = {
    name: "John",
    age: 30,
    isMarried: true,
    country: "USA"
};

// Get all keys in array
const keys = Object.keys(myObject);

// Get length of an array
const result = keys.length;

// Result:
console.log(result);
Enter fullscreen mode Exit fullscreen mode

Output

4
Enter fullscreen mode Exit fullscreen mode

The Object.keys() method returns an array of a given object's own enumerable string-keyed property names. (Source: MDN)


Thank you for reading

Thank you for reading my blog. πŸš€ you can read more awesome articles from my blog πŸš€πŸš€

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay