For..In loops in JavaScript – key value pairs

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


Solution 1:

for (var k in target){
    if (target.hasOwnProperty(k)) {
         alert("Key is " + k + ", value is " + target[k]);

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:

for (var k in target){
    if (typeof target[k] !== 'function') {
         alert("Key is " + k + ", value is" + target[k]);

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

Solution 2:

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

Object.keys(obj).forEach(function (key) {
   // do something with obj[key]

Solution 3:

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

const test = {a: 1, b: 2, c: 3};

for (const [key, value] of Object.entries(test)) {
  console.log(key, value);

Which will print out this output:

a 1
b 2
c 3

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

Hope it helps! =)

Solution 4:

The for in will work for you. If you think of an object as a map:

for(key in obj){
    // The key is key
    // The value is obj[key]

Solution 5:

var obj = {...};
for (var key in obj) {
    var value = obj[key];


The php syntax is just sugar.

Solution 6:

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 provides $.each [docs] which loops over both, array and object structures.