Search code examples
javascriptarraysecmascript-6es6-map

Better way to call `Array.prototype.some()` on es6 Map


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.


Solution

  • Use 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 comment 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);