Iterate over values of object
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);
});
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).
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 :)