- For..In loops in JavaScript — key value pairs
- 19 Answers 19
- Map.prototype.forEach()
- Try it
- Syntax
- Parameters
- Return value
- Description
- Examples
- Printing the contents of a Map object
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- For each key in javascript
- Перебор объекта обычными способами
- Методы для перебора объектов в Javascript
- Цикл for. in
- Метод Object.keys()
- Метод Object.values()
- Метод Object.entries()
- Заключение
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.
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 SiddhuSiddhu 389 1 gold badge 4 silver badges 8 bronze badges