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' }
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);
Output
4
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 🚀🚀
Top comments (0)