Javascript object for value

How to iterate over object keys and values in JavaScript

There are 4 ways to iterate over an object keys and values in JavaScript:

  1. The for. in loop is used for iterating over keys of objects, arrays, and strings.
  2. The Object.keys() method returns an array of object keys.
  3. The Object.values() method returns the values of all properties in the object as an array.
  4. The Object.entries() method returns an array of the object’s key-value pairs.

The Object.keys() method was added in ES6, whereas, Object.entries() and Object.values() methods were added in ES8. These methods convert the object into an array and then use array looping methods to iterate over that array.

The simplest and most popular way to iterate over an object’s keys and values is using the for. in loop:

const birds =  owl: '🦉', eagle: '🦅', duck: '🦆', chicken: '🐔' > for (const key in birds)  console.log(`$key> -> $birds[key]>`) > // owl -> 🦉 // eagle -> 🦅 // duck -> 🦆 // chicken -> 🐔 

The for. in loop works in all modern and old browsers, including Internet Explorer 6+. The only issue with the for. in loop is it iterates through the properties in the prototype chain. Since the JavaScript object inherits properties from its prototype, the for. in loop will iterate over those properties as well. However, you can use the hasOwnProperty() method to exclude inherited properties:

for (const key in birds)  if (birds.hasOwnProperty(key))  console.log(`$key> -> $birds[key]>`) > > 

The Object.keys() method takes an object as input and returns an array of the object’s own enumerable properties names:

const birds =  owl: '🦉', eagle: '🦅', duck: '🦆', chicken: '🐔' > const keys = Object.keys(birds) console.log(keys) // [ 'owl', 'eagle', 'duck', 'chicken' ] 
keys.forEach(key =>  console.log(`$key> -> $birds[key]>`) >) // owl -> 🦉 // eagle -> 🦅 // duck -> 🦆 // chicken -> 🐔 

The Object.values() method, unlike Object.keys() , returns an array of the given object’s own enumerable properties values:

const birds =  owl: '🦉', eagle: '🦅', duck: '🦆', chicken: '🐔' > Object.values(birds).forEach(item => console.log(item)) // 🦉 // 🦅 // 🦆 // 🐔 

The Object.entries() method returns an array of arrays, whereby each nested array has two elements. The first element is the property and the second element is the value.

const birds =  owl: '🦉', eagle: '🦅', duck: '🦆', chicken: '🐔' > const entries = Object.entries(birds) console.log(entries) // [ // [ 'owl', '🦉' ], // [ 'eagle', '🦅' ], // [ 'duck', '🦆' ], // [ 'chicken', '🐔' ] // ] 

To iterate over the nested array returned by Object.entries() , use the for. of loop or the forEach() method as shown below:

// => `for. of` Loop for (const [key, value] of Object.entries(birds))  console.log(`$key> -> $value>`) > // => `forEach()` Loop Object.entries(birds).forEach(([key, value]) =>  console.log(`$key> -> $value>`) >) 

You might also like.

Источник

Объекты: перебор свойств

Материал на этой странице устарел, поэтому скрыт из оглавления сайта.

Более новая информация по этой теме находится на странице https://learn.javascript.ru/object.

Для перебора всех свойств из объекта используется цикл по свойствам for..in . Эта синтаксическая конструкция отличается от рассмотренного ранее цикла for(;;) .

for..in

При этом for..in последовательно переберёт свойства объекта obj , имя каждого свойства будет записано в key и вызвано тело цикла.

Вспомогательную переменную key можно объявить прямо в цикле:

Так иногда пишут для краткости кода. Можно использовать и любое другое название, кроме key , например for(var propName in menu) .

Пример итерации по свойствам:

var menu = < width: 300, height: 200, title: "Menu" >; for (var key in menu) < // этот код будет вызван для каждого свойства объекта // ..и выведет имя свойства и его значение alert( "Ключ: " + key + " значение: " + menuJavascript object for value ); >

Обратите внимание, мы использовали квадратные скобки menuJavascript object for value . Как уже говорилось, если имя свойства хранится в переменной, то обратиться к нему можно только так, не через точку.

Количество свойств в объекте

Как узнать, сколько свойств хранит объект?

Готового метода для этого нет.

Самый кросс-браузерный способ – это сделать цикл по свойствам и посчитать, вот так:

var menu = < width: 300, height: 200, title: "Menu" >; var counter = 0; for (var key in menu) < counter++; >alert( "Всего свойств: " + counter );

В следующих главах мы пройдём массивы и познакомимся с другим, более коротким, вызовом: Object.keys(menu).length .

В каком порядке перебираются свойства?

Для примера, рассмотрим объект, который задаёт список опций для выбора страны:

Здесь мы предполагаем, что большинство посетителей из России, и поэтому начинаем с 7 , это зависит от проекта.

При выборе телефонного кода мы хотели бы предлагать варианты, начиная с первого. Обычно на основе списка генерируется select , но здесь нам важно не это, а важно другое.

Правда ли, что при переборе for(key in codes) ключи key будут перечислены именно в том порядке, в котором заданы?

По стандарту – нет. Но некоторое соглашение об этом, всё же, есть.

Соглашение говорит, что если имя свойства – нечисловая строка, то такие ключи всегда перебираются в том же порядке, в каком присваивались. Так получилось по историческим причинам и изменить это сложно: поломается много готового кода.

С другой стороны, если имя свойства – число или числовая строка, то все современные браузеры сортируют такие свойства в целях внутренней оптимизации.

К примеру, рассмотрим объект с заведомо нечисловыми свойствами:

var user = < name: "Вася", surname: "Петров" >; user.age = 25; // порядок перебора соответствует порядку присвоения свойства for (var prop in user) < alert( prop ); // name, surname, age >

А теперь – что будет, если перебрать объект с кодами?

Источник

How to loop through objects keys and values in Javascript?

A common problem faced by programers is looping over an enumerable dataset. This data can come in the form of arrays, lists, maps or other objects. In this article we will deal with this problem and learn 4 ways to loop through objects using javascript to retrieve multiple key-value pairs.

How to loop through objects in JavaScript?

The various methods that can be used to loop through objects in JavaScript are:

  1. Using a for. in loop
  2. Object.keys method
  3. Object.values method
  4. Object.entries method

Continue reading to learn more about the various methods.

Table of Contents

Introduction to looping through objects using javascript

If you have an array that is considered to be an object in javascript, you can’t loop through the array using map(), forEach(), or a for..of loop.

map() will give you TypeError: items.map is not a function:

forEach() will give you TypeError: items.forEach is not a function:

for..of will give you TypeError: items are not iterable:

Methods to loop through objects using javascript

for. in Loop

The most straightforward way to loop through an object’s properties is by using the for. in statement. This method works in all modern and old browsers including Internet Explorer 6 and higher.

Here is an example that uses the for. in loop to iterate over an object:

const user = < name: 'John Doe', email: '[email protected]', age: 25, dob: '08/02/1989', active: true >; // iterate over the user object for (const key in user) < console.log(`$: $`); > // name: John Doe // email: john.d[email protected] // age: 25 // dob: 08/02/1989 // active: true 

One problem in using the for. in method is that it loops through the properties in the prototype chain as well. Since the objects in JavaScript can inherit properties from their prototypes, the for. in statement will loop through those properties as well.

To avoid this problem, you have to explicitly check if the property belongs to the object by using the hasOwnProperty() method:

To overcome this hassle, later in ES8, two other methods were added, Object.entries() and Object.values(). These methods convert the object into an array and then use array looping methods to loop over that array.

Object.keys() Method

Before ES6, the only way to loop through an object was through using the for. in loop. The Object.keys() method was introduced in ES6 to make it easier to loop over objects.

It takes the object that you want to loop over as an argument and returns an array containing all properties names (or keys).

After which you can use any of the array looping methods, such as forEach(), to iterate through the array and retrieve the value of each property.

const courses = < java: 10, javascript: 55, nodejs: 5, php: 15 >; // convert object to key's array const keys = Object.keys(courses); // print all keys console.log(keys); // [ 'java', 'javascript', 'nodejs', 'php' ] // iterate over object keys.forEach((key, index) => < console.log(`$: $`); >); // java: 10 // javascript: 55 // nodejs: 5 // php: 15 

Object.values() Method

The Object.values() method was introduced in ES8 and it works opposite to that of Object.key(). It returns the values of all properties in the object as an array. You can then loop through the values array by using any of the array looping methods.

Let us look at an example:

const animals = < tiger: 1, cat: 2, monkey: 3, elephant: 4 >; // iterate over object values Object.values(animals).forEach(val => console.log(val)); // 1 // 2 // 3 // 4 

Object.entries() Method

The Object.entries(), an other ES8 method can be used for traversing an array. . Object.entries() outputs an array of arrays, with each inner array having two elements. The first element being the property and the second element is the value.

const animals = < tiger: 1, cat: 2, monkey: 3, elephant: 4 >; const entries = Object.entries(animals); console.log(entries); // [ [ 'tiger', 1 ], // [ 'cat', 2 ], // [ 'monkey', 3 ], // [ 'elephant', 4 ] ] 

To loop over the array returned by Object.entries(), you can either use the for. of loop or the forEach() method as shown below:

// `for. of` loop for (const Javascript object for value of Object.entries(animals)) < console.log(`$: $`); > // `forEach()` method Object.entries(animals).forEach((Javascript object for value) => < console.log(`$: $`) >); 

Parting Words

We have briefly seen about 4 different ways to loop through objects in javascript. If you are using old browsers, for. in is still a good option, otherwise, you can use any of the latest methods discussed above.

Источник

Читайте также:  Управление проектами
Оцените статью