For each key in javascript

For..In loops in JavaScript — key value pairs

I was wondering if there’s a way to do something like a PHP foreach loop in JavaScript. The functionality I’m looking for is something like this PHP Snippet:

foreach($data as $key => $value)

I was looking at the JS for..in loop, but there seems to be no way to specify the as . If I do this with a ‘normal’ for loop ( for(var i = 0; i < data.length; i++ ), is there a way to grab the key =>value pairs?

19 Answers 19

hasOwnProperty is used to check if your target really has that property, rather than having inherited it from its prototype. A bit simpler would be:

It just checks that k is not a method (as if target is array you’ll get a lot of methods alerted, e.g. indexOf , push , pop ,etc.)

Another way to iterate only over «own» properties is Object.keys . Object.keys(target).forEach(function (key) < targetFor each key in javascript; >); .

not going to work if target is created using Object.create(null) , code should be changed target.hasOwnProperty(k) -> Object.prototype.hasOwnProperty.call(target,k)

why not to use variables given in question example? What here is k , target and property ? For me, non-javascripter this area of undefined 🙂

I would say that almost every time you see obj.hasOwnProperty(k) it should be rewritten as Object.prototype.hasOwnProperty.call(obj, k) . If you don’t know whether or not an object has an own property k , then you probably also don’t know for sure whether it has an own property named «hasOwnProperty» ; and if it does, you don’t want that one, you want the one from Object.prototype . So IMO making hasOwnProperty a method at all was a design flaw in the language; nobody ever wants its behaviour to be overridden in practice.

If you can use ES6 natively or with Babel (js compiler) then you could do the following:

const test = ; for (const For each key in javascript of Object.entries(test))

Which will print out this output:

The Object.entries() method returns an array of a given object’s own enumerable property For each key in javascript pairs, in the same order as that provided by a for. in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

This works perfect, just wondering — compared to «for key in object and then get value by objectFor each key in javascript», which one gives better performance?

In this specific case I would assume it’s slower because of the Object.entries call. I didn’t run any tests though.

this is the best answer to the question at hand, which asked about grabbing both key and value in the for loop.

The accepted answer should be updated since this actually answers the question, although it wasn’t available at time of the question.

Читайте также:  Python tkinter разрешение экрана

You might want to check this question: stackoverflow.com/questions/47213651/… which seems to indicate that a syntax of this type would be recommended: Object.keys(myObject).forEach(key =>

No one has mentioned Object.keys so I’ll mention it.

Object.keys(obj).forEach(function (key) < // do something with objFor each key in javascript >); 

At this point you should be using an ES5 shim. If you’re living in the nice ES6 future use for of tc39wiki.calculist.org/es6/for-of

It is worth noting, that «There is no way to stop or break a forEach() loop other than by throwing an exception»

It doesn’t work on ES6 or I don’t understand it. Felix has a better and more readable answer below: data.forEach(function(value, index) < console.log(index); // 0 , 1, 2. >);

In modern JavaScript you can also do this:

for ( const For each key in javascript of Object.entries( obj ) )
var obj = ; for (var key in obj)

The php syntax is just sugar.

I assume you know that i is the key and that you can get the value via data[i] (and just want a shortcut for this).

ECMAScript5 introduced forEach [MDN] for arrays (it seems you have an array):

data.forEach(function(value, index) < >); 

The MDN documentation provides a shim for browsers not supporting it.

Of course this does not work for objects, but you can create a similar function for them:

function forEach(object, callback) < for(var prop in object) < if(object.hasOwnProperty(prop)) < callback(prop, object[prop]); >> > 

Since you tagged the question with jquery, jQuery provides $.each [docs] which loops over both, array and object structures.

Thanks a lot for your answer. I’ll read over the information you provided. Your assumption at the start of the answer was right, I knew that, except I got so much on my head with this project that I can’t focus and forgot about it.. Thank you.

There are three options to deal with keys and values of an object:

Object.values(obj).forEach(value => . ); 
Object.entries(obj).forEach((For each key in javascript) => . ); 
for (var key in myMap) < if (myMap.hasOwnProperty(key)) < console.log("key =" + key); console.log("value mt24"> 
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this answer
)">edited Jul 19, 2017 at 15:26
answered May 16, 2014 at 13:37
Add a comment |
9

You can use the for..in for that.

for (var key in data)
let test = ; Object.entries(test).forEach((For each key in javascript) => console.log(key, value)) // a 1 // b 2 // c 3 

You may add some explanation with the code you posted instead of posting a plain code which might be not understandable.

Object.entries pulls out an array of arrays based on the key/value pairs of the original object: [['a', 1],['b',2],['c',3]] . The forEach deconstructs each of the key/value arrays and sets the two variables to key and value , to be used as you want the in function - here output in console.log .

In the last few year since this question was made, Javascript has added a few new features. One of them is the Object.Entries method.

Copied directly from MDN is the follow code snippet

 const object1 = < a: 'somestring', b: 42 >; for (let For each key in javascript of Object.entries(object1)) < console.log(`$: $`); > 

ES6 will provide Map.prototype.forEach(callback) which can be used like this

myMap.forEach(function(value, key, myMap) < // Do something >); 

The forEach function does not contain the 'key' of the array but more the index of the element that you are currently iterating.

You can use a 'for in' loop for this:

Below is an example that gets as close as you get.

If you are using Lodash, you can use _.forEach

_.forEach(< 'a': 1, 'b': 2 >, function(value, key) < console.log(key + ": " + value); >); // => Logs 'a: 1' then 'b: 2' (iteration order is not guaranteed). 

Источник

Map.prototype.forEach()

The forEach() method executes a provided function once per each key/value pair in the Map object, in insertion order.

Try it

Syntax

forEach(callbackFn) forEach(callbackFn, thisArg) 

Parameters

A function to execute for each entry in the map. The function is called with the following arguments:

A value to use as this when executing callbackFn .

Return value

Description

The forEach method executes the provided callback once for each key of the map which actually exist. It is not invoked for keys which have been deleted. However, it is executed for values which are present but have the value undefined .

callback is invoked with three arguments:

  • the entry's value
  • the entry's key
  • the Map object being traversed

If a thisArg parameter is provided to forEach , it will be passed to callback when invoked, for use as its this value. Otherwise, the value undefined will be passed for use as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.

Each value is visited once, except in the case when it was deleted and re-added before forEach has finished. callback is not invoked for values deleted before being visited. New values added before forEach has finished will be visited.

Examples

Printing the contents of a Map object

The following code logs a line for each element in an Map object:

function logMapElements(value, key, map)  console.log(`map.get('$key>') = $value>`); > new Map([ ["foo", 3], ["bar", >], ["baz", undefined], ]).forEach(logMapElements); // Logs: // "map.get('foo') = 3" // "map.get('bar') = [object Object]" // "map.get('baz') = undefined" 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 12, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

For each key in javascript

Методы перебора объектов с помощью javascript | How to loop through objects keys and values in Javascript

Распространенная проблема, с которой сталкиваются программисты - это как перебрать набор данных. Эти данные могут поступать в виде массивов, списков, таблиц или других объектов. В этой статье мы рассмотрим эту проблему и узнаем 4 способа перебора объектов с помощью Javascript для получения необходимых пар ключ-значение.

Перебор объекта обычными способами

Если у вас есть массив данных, который является объектом в Javascript, вы не сможете перебрать его с помощью таких методов, как map() , forEach() или цикла for..of . Вы просто получите ошибку.

map() выдаст вам TypeError: items.map is not a function:

forEach() выдаст вам TypeError: items.forEach is not a function:

for..of выдаст вам TypeError: items are not iterable:

Методы для перебора объектов в Javascript

Цикл for. in

Самый простой способ перебрать свойства объекта - использовать оператор for. in . Этот метод работает во всех современных и старых браузерах, включая Internet Explorer 6 и выше.

Вот пример, в котором цикл for. in используется для перебора объекта:

const user = < name: 'Иван Пeтров', email: 'petrov@mail.com', age: 25, date: '08/02/1989', active: true >; for (const key in user) < console.log(key + ':', userFor each key in javascript); >// name: Иван Пeтров // email: petrov@mail.com // age: 25 // date: 08/02/1989 // active: true

Одна из проблем при использовании цикла for. in заключается в том, что он также перебирает свойства в цепочке прототипов. Поскольку объекты в JavaScript могут наследовать свойства от своих прототипов, оператор for. in также будет перебирать эти свойства.

Чтобы избежать этой проблемы, необходимо явно проверить, принадлежит ли свойство объекту, используя метод hasOwnProperty() :

Чтобы преодолеть эту проблему, позже в ES8 были добавлены два других метода: Object.entries() и Object.values() . Эти методы преобразовывают объект в массив, чтобы потом использовать методы перебора массива.

Метод Object.keys()

До спецификации ES6 единственным способом перебрать объект был цикл for. in . Метод Object.keys() был введен в ES6, чтобы упростить перебор объектов.

Он принимает объект, который вы хотите перебрать в качестве аргумента, и возвращает массив, содержащий все имена свойств (или ключи). После этого вы можете использовать любой из методов перебора массива, например forEach() , для перемещения по массиву и получения значения каждого свойства.

const courses = < java: 10, javascript: 55, nodejs: 5, php: 15 >; const keys = Object.keys(courses); console.log(keys); // [ 'java', 'javascript', 'nodejs', 'php' ] keys.forEach((key, index) => < console.log(key + ':', coursesFor each key in javascript); >); // java: 10 // javascript: 55 // nodejs: 5 // php: 15

Метод Object.values()

Метод Object.values() был введен в ES8 и работает противоположно методу Object.key() . Он возвращает значения всех свойств объекта в виде массива. Затем вы можете перебрать полученный массив, используя любой из методов цикла.

Давайте посмотрим на примере:

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

Метод Object.entries()

Метод ES8 Object.entries() используется для преобразования объекта. Object.entries() выводит массив массивов, где каждый внутренний массив состоит из двух элементов. Первый элемент - это свойство, а второй - значение.

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 ] ]

А уже чтобы перебрать массив, возвращаемый Object.entries() , вы можете использовать цикл for. of или метод forEach() :

// `for. of` цикл for (const For each key in javascript of Object.entries(animals)) < console.log(key, value); >// `forEach()` метод Object.entries(animals).forEach((For each key in javascript) => < console.log(key, value) >);

Заключение

Мы вкратце рассмотрели 4 различных способа перебора объектов в Javascript. Если вы используете старые браузеры, for. in по-прежнему является хорошим вариантом; в противном случае вы можете использовать любой из новых методов, описанных выше.

Источник

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