Как узнать длину объекта js

от admin

Количество элементов в объекте (object length)

В данном посте мы разберем как проверить сколько элементов содержит объект и напишем функцию для проверки объекта на пустоту.

В JavaScript у объектов нет свойства length , как у массивов. Поэтому мы не можем просто написать obj.length , чтобы получить «длину объекта». Но мы можем сделать это другим способом.

Как проверить количество элементов в объекте JS?

Для этого мы можем воспользоваться методом Object.keys() , чтобы получить все ключи в массив и затем уже у массива воспользоваться свойством length , чтобы получить количество элементов:

Теперь на основании этого давайте напишем функцию, которая будет показывать длину объекта, а сам объект мы будем передавать параметром в эту функцию:

Также есть второй вариант, сделать это с помощью цикла for in по объекту:

Для чего мы тут используем hasOwnProperty вы можете разобраться в этой статье.

Также можно добавить отдельный метод глобальному объекту и вызывать его при необходимости:

Проверка на пустой объект

Чтобы проверить объект на пустоту и узнать есть ли там хоть один элемент, мы можем написать следующую функцию:

В зависимости от вашей задачи, можно также добавить проверку объект ли нам вообще попал в параметр или нет.

Get Length of JavaScript Object

Objects are used to store a set of properties, each of which can be thought of as a link between a name (or key) and a value (a collection of key-value pairs).

In this guide, we will learn how to get the length of a JavaScript object.

Checking the length of an Object is not a common and basic operation; however, it is critical to understand how this can be accomplished and to avoid some unnecessary bugs. The object does not have a length property by default. The length property is only available to arrays and strings.

There are basically two ways to get the length of an object in JavaScript: using any of the object static methods or the for. in loop method. Let's start by creating an object, either with the object literal syntax or using the new keyword:

Get Length of Object With Object Static Methods

Static methods are pre-defined methods that we can access on any object. To determine the length of an object, we can use object static methods such as Object.keys() , Object.values() , and Object.entries() . These methods return either the key, values, or key-value pairs as arrays, allowing us to use the length property to determine the object's length.

Note: Properties are key-value pairs that define an object. Each property in an object is given a name (also known as a key) and a value (also known as a value). Depending on which properties you want to enumerate, you can extract keys() and values() separately, or entries() , which are key-value pairs.

Get Length of Object With Object.keys()

The Object.keys() method returns an array of properties of the Object , we will then make use of the length property to get the number of elements in the array(length of the object). For example, making use of the object we created at the beginning of this article:

Get Length of Object With Object.values()

The Object.values() method returns an array which contains the values of the Object . We will also make use of the length property to get the number of elements. For example, making use of the object we created at the beginning of this article:

Get Length of Object With Object.entries()

The Object.entries() method returns an array of the key-value pair of an Object . We can use the length property to get the number of elements. For example, making use of the object we created at the beginning of this article:

Get Length of Object Using for…in Loop

The for…in loop is used to iterate the properties of the object. To get the length, all we would so is to create a variable and increase the counter as long as the loop continues.

Conclusion

In this article, we have learned how to get the length of an object via either static methods or looping through via the for…in method.

Как узнать длину объекта js

Method 1: Using the Object.keys() method

Читать:
Кому не стоит идти в программисты

The Object.keys() method is used to return the object property name as an array. The length property is used to get the number of keys present in the object. It gives the length of the object.

Syntax:

Example:

Output:

Find the length of a JavaScript object

Method 2: Loop through all the fields of the object and check their property

The hasOwnProperty() method is used to return a boolean value indicating whether the object has the specified property as its own property. This method can be used to check if each key is present in the object itself. The contents of the object are looped through and if the key is present, the total count of keys is incremented. This gives the length of the object.

How to Get an Object Length

Code Tidbit by SamanthaMing.com

Unlike arrays, it’s always been tricky to get the object length. Well no more!
Object.keys return an array of all the object’s enumerable property keys. And after that, you can simply call length , and voila! You have the length of the object ��

Why can’t we call length on an Object

You might be wondering why can’t we just simply call length directly on our object. Let’s see what happens when we do:

You can’t do it because object doesn’t have a length property. Only string and arrays have a length property.

What are Enumerables

Alright, let’s cover another topic. I mentioned at the beginning that Object.keys returns an array of enumerable property keys. So let’s figure out where this enumerable attribute comes from.

Assigning a Property

Typically, when we want to add a property to an object, we might just use the dot notation:

Defining a Property

Alternatively, we can also use Object.defineProperty . It accepts 3 parameters. And it’s in the property descriptor where we can set our enumerable attribute.

Alright, let’s define a property with this method:

Hmmm. that’s odd. Why didn’t our property show up �� Well, that’s because when we define a property this way, the enumerable attribute is by default false . So if we want it to show up, we need to set true to it.

Enumerable defaults to true

Let’s go back to our object property example that we set with the dot notation. Why did it show up automatically? Well, that’s because when we assign a property that way, the enumerable attribute is automatically set to true .

Enumerable Summary

For most of us, we would rarely touch the enumerable attribute when defining our property. It’s simply a way for us to control if the particular property we created will show up or stay hidden when we iterate over the object using Object.keys .

If you want to learn more about enumerability, I recommend reading this article, Enumerability in ECMAScript 6.

Therefore, the attribute enumerable is used to hide properties that should not be iterated over. That was the reason for introducing enumerability in ECMAScript 1.

Dr. Axel Rauschmayer, 2Ality

Object.keys vs Object.getOwnPropertyNames

Now that you understand enumerable , let’s cover another method that you might see as an option to get the length, Object.getOwnPropertyNames .

As you can see Object.getOwnPropertyNames will return ALL property keys, whereas Object.keys will just return the enumerable property keys. As I mentioned before, enumerable attributes are maybe hidden for a reason, so you might not want to access that. Therefore, Object.getOwnPropertyName might not be the method you want to use to get the length of an object.

Object Length with Symbols

Before you default to Object.keys to get the object length. I want to point out one more consideration. In ECMAScript 6, ES6, a new primitive data type was introduced called symbol . And you can use symbol as a property name on an object.

But the gotcha is when you have a symbol as a property name. Object.keys nor Object.getOwnPropertyNames will work.

So a solution is to use Object.getOwnPropertySymbols

Now combining the two methods, you will get the proper length.

Community Input

@Eugene Karataev: Chrome displays the non-enumerable properties in the console. It just shows them slightly differently — not as bright as the enumerable ones

Похожие статьи