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 [
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.
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.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With