有没有一个简单的方法来合并ES6映射在一起(像Object.assign)?说到这里,ES6集合(比如Array.concat)呢?


当前回答

将集合转换为数组,将它们平直,最后构造函数将惟一化。

const union = (...sets) => new Set(sets.map(s => [...s]).flat());

其他回答

以下是我使用生成器的解决方案:

地图:

let map1 = new Map(), map2 = new Map();

map1.set('a', 'foo');
map1.set('b', 'bar');
map2.set('b', 'baz');
map2.set('c', 'bazz');

let map3 = new Map(function*() { yield* map1; yield* map2; }());

console.log(Array.from(map3)); // Result: [ [ 'a', 'foo' ], [ 'b', 'baz' ], [ 'c', 'bazz' ] ]

集:

let set1 = new Set(['foo', 'bar']), set2 = new Set(['bar', 'baz']);

let set3 = new Set(function*() { yield* set1; yield* set2; }());

console.log(Array.from(set3)); // Result: [ 'foo', 'bar', 'baz' ]

集:

var merged = new Set([...set1, ...set2, ...set3])

地图:

var merged = new Map([...map1, ...map2, ...map3])

注意,如果多个映射具有相同的键,则合并映射的值将是具有该键的最后一个合并映射的值。

例子

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

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

    return dataMap
}

使用

const map = mergedMaps(new Map([[1, false]]), new Map([['foo', 'bar']]), new Map([['lat', 1241.173512]]))
Array.from(map.keys()) // [1, 'foo', 'lat']

你可以使用spread语法将它们合并在一起:

const map1 = {a: 1, b: 2}
const map2 = {b: 1, c: 2, a: 5}

const mergedMap = {...a, ...b}

=> {a: 5, b: 1, c: 2}

当向现有集合中添加多个元素(来自数组或另一个集合)时,调用new Set(…anArrayOrSet)没有任何意义。

我在reduce函数中使用了这个,它只是简单的愚蠢。即使你有…数组展开运算符可用,在这种情况下不应该使用它,因为它浪费处理器、内存和时间资源。

// Add any Map or Set to another
function addAll(target, source) {
  if (target instanceof Map) {
    Array.from(source.entries()).forEach(it => target.set(it[0], it[1]))
  } else if (target instanceof Set) {
    source.forEach(it => target.add(it))
  }
}

演示片段

// Add any Map or Set to another function addAll(target, source) { if (target instanceof Map) { Array.from(source.entries()).forEach(it => target.set(it[0], it[1])) } else if (target instanceof Set) { source.forEach(it => target.add(it)) } } const items1 = ['a', 'b', 'c'] const items2 = ['a', 'b', 'c', 'd'] const items3 = ['d', 'e'] let set set = new Set(items1) addAll(set, items2) addAll(set, items3) console.log('adding array to set', Array.from(set)) set = new Set(items1) addAll(set, new Set(items2)) addAll(set, new Set(items3)) console.log('adding set to set', Array.from(set)) const map1 = [ ['a', 1], ['b', 2], ['c', 3] ] const map2 = [ ['a', 1], ['b', 2], ['c', 3], ['d', 4] ] const map3 = [ ['d', 4], ['e', 5] ] const map = new Map(map1) addAll(map, new Map(map2)) addAll(map, new Map(map3)) console.log('adding map to map', 'keys', Array.from(map.keys()), 'values', Array.from(map.values()))