Is there a simple way to merge ES6 Maps together (like Object.assign
)? And while we're at it, what about ES6 Sets (like Array.concat
)?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
For sets:
For maps:
Note that if multiple maps have the same key, the value of the merged map will be the value of the last merging map with that key.
Here's my solution using generators:
For Maps:
For Sets:
For reasons I do not understand, you cannot directly add the contents of one Set to another with a built-in operation.
It would seem a natural for
.add()
to have detected that you were passing another Set object and then just grab all the items out of that Set (which is how my own Set object -before there was an ES6 Set specification) works. But, they chose not to implement it that way.Instead, you can do it with a single
.forEach()
line:And, for a
Map
, you could do this:The approved answer is great but that creates a new set every time.
If you want to mutate an existing object instead, use a helper function.
Set
Usage:
Map
Usage:
To merge the sets in the array Sets, you can do
It is slightly mysterious to me why the following, which should be equivalent, fails at least in Babel:
Original Answer
I would like to suggest another approach, using
reduce
and thespread
operator:Implementation
Usage:
Tip:
We can also make use of the
rest
operator to make the interface a bit nicer:Now, instead of passing an array of sets, we can pass an arbitrary number of arguments of sets: