Simplest way to merge ES6 Maps/Sets?

2019-01-13 00:37发布

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)?

9条回答
叛逆
2楼-- · 2019-01-13 01:04

Example

const mergedMaps = (...maps) => {
    const dataMap = new Map([])

    for (const map of maps) {
        for (const [key, value] of map) {
            dataMap.set(key, value)
        }
    }

    return dataMap
}

Usage

const map = mergedMaps(new Map([[1, false]]), new Map([['foo', 'bar']]), new Map([['lat', 1241.173512]]))
Array.from(map.keys()) // [1, 'foo', 'lat']
查看更多
Melony?
3楼-- · 2019-01-13 01:04

Object.assign can be used for merging maps:

merged = Object.assign({}, first, second)
查看更多
地球回转人心会变
4楼-- · 2019-01-13 01:05

No, there are no builtin operations for these, but you can easily create them your own:

Map.prototype.assign = function(...maps) {
    for (const m of maps)
        for (const kv of m)
            this.add(...kv);
    return this;
};

Set.prototype.concat = function(...sets) {
    const c = this.constructor;
    let res = new (c[Symbol.species] || c)();
    for (const set of [this, ...sets])
        for (const v of set)
            res.add(v);
    return res;
};
查看更多
登录 后发表回答