I recently converted some code that made use of regular objects as maps to the new es6 Map
class. I encountered an issue pretty quickly as, while the Map
class includes a forEach
like Array
, it does not include a some
method along with many other Array.prototype
methods.
To give some context, the original code with regular JS objects looked something like this:
var map = {
entry1: 'test',
entry2: 'test2'
};
Object.keys(map).some(key => {
var value = map[key];
// Do something...found a match
return true;
});
The Map
class does include an entries
method but sadly this returns an Iterator
object. This doesn't include any easy way to access the Array.prototype
methods either.
I'm curious if there's a clean way to do this or if I'm barking up the wrong tree.
I recently converted some code that made use of regular objects as maps to the new es6 Map
class. I encountered an issue pretty quickly as, while the Map
class includes a forEach
like Array
, it does not include a some
method along with many other Array.prototype
methods.
To give some context, the original code with regular JS objects looked something like this:
var map = {
entry1: 'test',
entry2: 'test2'
};
Object.keys(map).some(key => {
var value = map[key];
// Do something...found a match
return true;
});
The Map
class does include an entries
method but sadly this returns an Iterator
object. This doesn't include any easy way to access the Array.prototype
methods either.
I'm curious if there's a clean way to do this or if I'm barking up the wrong tree.
Share Improve this question asked Jan 8, 2017 at 22:07 KhalilRavannaKhalilRavanna 6,0583 gold badges29 silver badges25 bronze badges 2- stackoverflow./questions/29886552/… – Ruan Mendes Commented Jan 8, 2017 at 22:12
- Related: stackoverflow./questions/27612713/… – Paul Commented Jan 8, 2017 at 22:20
2 Answers
Reset to default 10Use the Map#values
to get an iterator of the values, and the spread syntax
or Array#from
(a question of style) to convert the iterator to an array:
const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
const result = [...map.values()].some((value) => value > 2);
console.log(result);
As noted in @Paulpro ment you can use the same method to iterate Map#entries
, and Map#keys
. For example, using Array#reduce
to convert the Map to an object. As Array#from
invokes Map#entries
we don't need to call it explicitly:
const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
const result = Array.from(map.entries()).reduce((obj, [key, value]) => {
obj[key] = value;
return obj;
}, {});
console.log(result);
Call Array.from
upon the Map
object and invoke some
on that:
Array.from(map).some(([key, value]) => /* something */ true)
Of course that's horribly inefficient. A much better idea is to define a some
function that does work on any iterator, such as the ones that Map
provides:
function some(it, pred) {
for (const v of it)
if (pred(v))
return true;
return false;
}
some(map.values(), value => /* something */ true)