Javascript object key length

doctor Brain

В JavaScript почти все является объектом. Объекты используются для хранения информации в парах ключ-значение, где значения могут быть представлены данными различных типов или функциями. В отличие от массивов и строк, объекты не располагают встроенным свойством length, определяющим их размеры.

В этом легко убедиться: попробуйте вызвать свойства length для объекта — ответом будет undefined. Тем не менее, существуют простые приемы, позволяющие узнать длину объекта в JavaScript.

Object.keys()

Метод Object.keys() возвращает массив ключей. Несложно догадаться, как теперь определить размер самого объекта:

const address = < city: 'Bngalore', name: 'John', job: 'Software' >console.log(Object.key(address).length); 

Цикл for… in

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

let count = 0; for (let key in address) < count++ >console.log(count); 

Добавить свойств length в прототип объекта

Добавив свойство length к прототипу объекта, мы сможем повторно использовать его во всем приложении:

if (!Object.prototype.length) < Object.defineProperty(Object.prototype, 'length', < get: function() < return Object.keys(this).length >>) > console.log(address.length); 

Надеюсь эта информация была полезной.

Новые публикации

Photo by CHUTTERSNAP on Unsplash

JavaScript: сохраняем страницу в pdf

HTML: Полезные примеры

CSS: Ускоряем загрузку страницы

JavaScript: 5 странностей

JavaScript: конструктор сортировщиков

Категории

О нас

Frontend & Backend. Статьи, обзоры, заметки, код, уроки.

© 2021 dr.Brain .
мир глазами веб-разработчика

Источник

How to Get the Length of an Object in JavaScript?

Javascript Course - Mastering the Fundamentals

An object is a collection of key values linked as links between names and values. It is important to understand how to check the length of an object in order to avoid unnecessary bugs. Checking the object length in javascript isn’t a common and fundamental operation; however, it is crucial to understand how to do so. There is no default length property on the object. It is only available to arrays and strings that have the length property.

Introduction

Objects are collections of key-value pairs that have properties that are linked by their names. Understanding how to find the object’s length is not a common and basic operation, but in order to avoid unnecessary bugs, it is essential to know how it can be done. There is no length property by default on the object. It is only available to arrays and strings that have the length property. A JavaScript object’s length can be determined by either using one of its static methods or by using the for. in loop method. Let us explore them one by one

Читайте также:  Php вывод json массива

Method 1: Using the Object.keys() Method

An object’s length can be obtained by calling the Object.keys() method and accessing the length property, such as Object.keys(obj).length . A given object’s key name is returned by Object.keys(); its length is returned by its length property.

This example shows how we can find the length of an object with three fields using Object.keys().

Method 2: How to Loop through All the Fields of the Object and Check Their Property

A boolean value is returned by the hasOwnProperty() method indicating whether the specified property belongs to the object. It is possible to check whether each key is present within the object by using this method. Each key in the object is looped through, and if it is present, the total number of keys is increased. In this way, you can find out the object’s length from this.

This example shows how we can loop through the object with three fields using the hasOwnProperty() method. We loop through all the 3 fields inside the user and display it as output using hasOwnProperty() method.

Get Length of Object with Object.values()

The Object.values() method returns a list of the enumerable property values associated with the object. As a next step, we will use the object’s length property to determine how many elements there are in the array (length of the object).

This example shows how we can find the length of an object with three fields using Object.values() .

Get Length of Object with Object.entries()

The Object.entries() method returns a collection of string-keyed properties Javascript object key length on your object. We will then use the length property to determine the number of elements.

This example shows how we can find the length of an object with three fields using Object.entries().

Get Length of Object Using for…in Loop

In the for. in statement, all enumerable properties of an object, including inherited enumerable properties, are iterated over (ignoring ones keyed by symbols).

This example shows how we can find the length of an object with three fields using for..in the loop.

Object.keys vs Object.getOwnPropertyNames

The Object.getOwnPropertyNames() method returns the names of all the properties owned by an object. The Object.keys() method returns all the object’s enumerable properties. If you don’t set enumerable: false to any property, both return the same result.

The student object has two properties, including its name and age.

Читайте также:  Ym komus ru portalclienttocan index php

Let’s define another property named Class but set it to enumerable: false:

In JavaScript, a property is enumerable if it can be read while being iterated using the for. in the loop or the Object. keys() function.

Object.keys do not include the resolution property:

Object Length with Symbols

The symbol primitive data type was introduced in ECMAScript 6. It returns an array of all symbol properties found directly on an object using the getOwnPropertySymbol() method.

This example shows how we can find the length of an object with three fields using getOwnPropertySymbol() method.

Conclusion

  1. We explored about the various ways we could use to find the length of objects using Object.values() , Object.entries() and by using for..in loop
  2. The length property of the Object.keys() method is perhaps the simplest and fastest way to obtain the length of an object in JavaScript.
  3. Both static and for..in loop would do the job for you but most programmers prefer the object static method only
  4. Finding the length of javascript objects is not as easy as finding the length for arrays it is quite complicated but can be solved by using the methods listed in this article

Источник

# How to Get an Object Length

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 🎉

const object =  one: '1️⃣', two: '2️⃣' >; // Using Lodash _.size(object); // 2 // Using JavaScript Object.keys(object).length; // 2 

# 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:

const object =  one: '1️⃣', two: '2️⃣' >; object.length; // undefined object.hasOwnProperty('length'); // false 

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

const string = 'hello'; const array = [1, 2, 3]; string.hasOwnProperty('length'); // true array.hasOwnProperty('length'); // true 

# 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:

const object = >; object.one = '1️⃣'; console.log(object); // 

# 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.

Object.defineProperty(object name, property name, property descriptor) 

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

const object = >; Object.defineProperty(object, 'one',  value: '1️⃣', >); console.log(object); // <> // ☝️ Why is it empty? 🤔 

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.

const object = >; Object.defineProperty(object, 'one',  value: '1️⃣', enumerable: true, // 👈 >); console.log(object); // // ☝️ Great, it shows up now! 

# 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 .

const object = >; object.one = '1️⃣'; object.propertyIsEnumerable('one'); // 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 .

const object =  one: '1️⃣' >; Object.defineProperty(object, 'two',  value: '2️⃣', enumerable: false, >); Object.keys(object); // [ 'one' ] Object.getOwnPropertyNames(object); // [ 'one', 'two' ] 

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.

const animal =  [Symbol('ghost')]: '👻', turtle: '🐢', >; 

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

Object.keys(animal); // [ 'turtle' ] Object.getOwnPropertyNames(animal); // [ 'turtle' ] 

So a solution is to use Object.getOwnPropertySymbols

Object.getOwnPropertySymbols(animal); // [ Symbol(ghost) ] 

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

const enumerableLength = Object.keys(animal).length; const symbolLength = Object.getOwnPropertySymbols(animal).length; const totalObjectLength = enumerableLength + symbolLength; // 2 

Источник

Оцените статью