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?

This question is tagged with javascript foreach

~ Asked on 2011-08-30 10:34:19

The Best Answer is


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

~ Answered on 2011-08-30 10:37:00


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

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

~ Answered on 2011-08-30 10:52:53

Most Viewed Questions: