Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 411
KhalilRavanna Avatar asked Jan 08 '17 22:01

KhalilRavanna


People also ask

What are the array methods introduced in ES6?

Some new array methods are introduced in ES6, such as Array.of (), Array.from (), and many more. The array methods introduced in ES6 are tabulated below. 1. It converts array-like values and iterable values into arrays.

What is map () method in ES6?

The map () method was introduced in ES6. With this method, we can access and perform a consistent action on every single item inside an array collection. It takes in a callback function which it calls for every new element it iterates over.

Why can't I use map() when returning an array?

Since map builds a new array, using it when you aren't using the returned array is an anti-pattern; use forEach or for...of instead. you're not returning a value from the callback.

What is the difference between ES5 filter() and ES6 find() methods?

Note: ES6 find () method is not similar to the ES5 filter () method because the filter () method always returns an array of matches (return multiple matches), but find () method always returns the actual statement. The Array.prototype.findIndex () method returns the index of the first element of the given array that satisfies the given condition.


1 Answers

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);
like image 170
Ori Drori Avatar answered Sep 22 '22 16:09

Ori Drori