Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate map's key and values using for..of in Node?

I am using Node v5.4.1 and I can't interate over a map's key and values using the for..of loop outlined on MDN.

Using the following code:

var map = new Map();
map.set(1, 'hello');
map.set(2, 'world');

for (var [key, value] of map.entries()) {
    console.log(key + " = " + value);
}

Results in the syntax error:

for (var [key, value] of map.entries()) {
         ^

SyntaxError: Unexpected token [
like image 633
Corey Avatar asked Apr 20 '16 14:04

Corey


People also ask

How do you iterate over object keys and values?

You have to pass the object you want to iterate, and the JavaScript Object. keys() method will return an array comprising all keys or property names. Then, you can iterate through that array and fetch the value of each property utilizing an array looping method such as the JavaScript forEach() loop.

How would you iterate over the key-value pairs from an instance of Map?

Iterating over Map. entrySet() method returns a collection-view(Set<Map. Entry<K, V>>) of the mappings contained in this map. So we can iterate over key-value pair using getKey() and getValue() methods of Map.

What is the difference between for of and for in?

Difference between for...of and for...in The main difference between them is in what they iterate over. The for...in statement iterates over the enumerable string properties of an object, while the for...of statement iterates over values that the iterable object defines to be iterated over.

Can we loop an object which is like key-value pairs?

Object. key(). It returns the values of all properties in the object as an array. You can then loop through the values array by using any of the array looping methods.


1 Answers

Node still doesn't support destructuring. Barring the use of a transpiler, you can do it manually though:

for (var entry of map.entries()) {
    var key = entry[0],
        value = entry[1];
    console.log(key + " = " + value);
}
like image 52
Bergi Avatar answered Oct 23 '22 18:10

Bergi