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 s
19

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

  • Object.entries documentation
  • for…of documentation
  • Destructuring assignment documentation
  • Enumerability and ownership of properties documentation

Leave a Comment