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



Solution 1:[1]

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 for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

Solution 2:[2]

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 3:[3]

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

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

Solution 4:[4]

for...in will work for you.

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

In modern JavaScript you can also do this:

for ( const [key,value] of Object.entries( obj ) ) {

}

Solution 5:[5]

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

}

The php syntax is just sugar.

Solution 6:[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.

Solution 7:[7]

You can use the for..in for that.

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

Solution 8:[8]

for (var key in myMap) {
    if (myMap.hasOwnProperty(key)) {
        console.log("key =" + key);
        console.log("value =" + myMap[key]);
    }
}

In javascript, every object has a bunch of built-in key-value pairs that have meta-information. When you loop through all the key-value pairs for an object you're looping through them too. The use of hasOwnProperty() filters these out.

Solution 9:[9]

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

  1. Select values:

    Object.values(obj).forEach(value => ...);
    
  2. Select keys:

    Object.keys(obj).forEach(key => ...);
    
  3. Select keys and values:

    Object.entries(obj).forEach(([key, value]) => ...);
    

Solution 10:[10]

let test = {a: 1, b: 2, c: 3};
Object.entries(test).forEach(([key, value]) => console.log(key, value))

// a 1
// b 2
// c 3

Solution 11:[11]

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 [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}

Solution 12:[12]

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

myMap.forEach(function(value, key, myMap) {
                        // Do something
                    });

Solution 13:[13]

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

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

Solution 14:[14]

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

for(var key in data){
  var value = data[key];    
  //your processing here
}

If you're using jQuery see: http://api.jquery.com/jQuery.each/

Solution 15:[15]

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

Solution 16:[16]

why not simply this

var donuts = [
{ type: "Jelly", cost: 1.22 },
{ type: "Chocolate", cost: 2.45 },
{ type: "Cider", cost: 1.59 },
{ type: "Boston Cream", cost: 5.99 }];

donuts.forEach(v => {console.log(v["type"]+ " donuts cost $"+v["cost"]+" each")});

Solution 17:[17]

Please try the below code:

<script> 
 const games = {
  "Fifa": "232",
  "Minecraft": "476",
  "Call of Duty": "182"
 };

Object.keys(games).forEach((item, index, array) => {
  var msg = item+' '+games[item];
  console.log(msg);
});

Solution 18:[18]

yes, you can have associative arrays also in javascript:

var obj = 
{
    name:'some name',
    otherProperty:'prop value',
    date: new Date()
};
for(i in obj)
{
    var propVal = obj[i]; // i is the key, and obj[i] is the value ...
}