I want to iterate over all values of a map. I know it's possible to iterate over all keys. But is it possible to iterate directly over the values?
var map = { key1 : 'value1', key2 : 'value2' }
for (var key in map) { ...} // iterates over keys
Object. It takes the object that you want to loop over as an argument and returns an array containing all properties names (or keys). After which you can use any of the array looping methods, such as forEach(), to iterate through the array and retrieve the value of each property.
entries() is the recommended method for iterating over an object's properties in JavaScript. Since the method returns a multidimensional array, we can greatly simplify our code by using the array destructuring syntax to retrieve each property into a separate variable.
It's not a map. It's simply an Object
.
Edit: below code is worse than OP's, as Amit pointed out in comments.
You can "iterate over the values" by actually iterating over the keys with:
var value;
Object.keys(map).forEach(function(key) {
value = map[key];
console.log(value);
});
I iterate like this and it works for me.
for (let [k, v] of myMap) {
console.log("Key: " + k);
console.log("Value: " + v);
}
Hope this helps :)
In the sense I think you intended, in ES5 or ES2015, no, not without some work on your part.
In ES2016, probably with object.values
.
Mind you Arrays in JavaScript are effectively a map from an integer to a value, and the values in JavaScript arrays can be enumerated directly.
['foo', 'bar'].forEach(v => console.log(v)); // foo bar
Also, in ES2015, you can make an object iterable by placing a function on a property with the name of Symbol.iterator
:
var obj = {
foo: '1',
bar: '2',
bam: '3',
bat: '4',
};
obj[Symbol.iterator] = iter.bind(null, obj);
function* iter(o) {
var keys = Object.keys(o);
for (var i=0; i<keys.length; i++) {
yield o[keys[i]];
}
}
for(var v of obj) { console.log(v); } // '1', '2', '3', '4'
Also, per other answers, there are other built-ins that provide the functionality you want, like Map
(but not WeakMap
because it is not iterable) and Set
for example (but these are not present in all browsers yet).
EcmaScript 2017 introduced Object.entries
that allows you to iterate over values and keys. Documentation
var map = { key1 : 'value1', key2 : 'value2' }
for (let [key, value] of Object.entries(map)) {
console.log(`${key}: ${value}`);
}
The result will be:
key1: value1
key2: value2
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