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
This question is related to
javascript
dictionary
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
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 case you want to deeply iterate into a complex (nested) object for each key & value, you can do so using Object.keys():
const iterate = (obj) => {
Object.keys(obj).forEach(key => {
console.log(`key: ${key}, value: ${obj[key]}`)
if (typeof obj[key] === 'object') {
iterate(obj[key])
}
})
}
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).
You could use underscore.js and the each function:
_.each({key1: "value1", key2: "value2"}, function(value) {
console.log(value);
});
Source: Stackoverflow.com