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


当前回答

当向现有集合中添加多个元素(来自数组或另一个集合)时,调用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()))

其他回答

有几种方法可以做到。你可以使用地图。合并功能:

let mergedMap = map1.merge(map2);

注意:如果任何Map的键是相同的,将使用最后一个要合并的Map中的重复键的值。

更多信息请点击这里:https://untangled.io/immutable-js-6-ways-to-merge-maps-with-full-live-examples/#:~:text=merge(),merged%20in%20will%20be%20used。

我创建了一个helper方法来合并映射,并以所需的任何成对方式处理重复键的值:

const mergeMaps = (map1, map2, combineValuesOfDuplicateKeys) => {
  const mapCopy1 = new Map(map1);
  const mapCopy2 = new Map(map2);

  mapCopy1.forEach((value, key) => {
    if (!mapCopy2.has(key)) {
      mapCopy2.set(key, value);
    } else {
      const newValue = combineValuesOfDuplicateKeys
        ? combineValuesOfDuplicateKeys(value, mapCopy2.get(key))
        : mapCopy2.get(key);
      mapCopy2.set(key, newValue);
      mapCopy1.delete(key);
    }
  });

  return new Map([...mapCopy1, ...mapCopy2]);
};

const mergeMaps = (map1, map2, combineValuesOfDuplicateKeys) => { const mapCopy1 = new Map(map1); const mapCopy2 = new Map(map2); mapCopy1.forEach((value, key) => { if (!mapCopy2.has(key)) { mapCopy2.set(key, value); } else { const newValue = combineValuesOfDuplicateKeys ? combineValuesOfDuplicateKeys(value, mapCopy2.get(key)) : mapCopy2.get(key); mapCopy2.set(key, newValue); mapCopy1.delete(key); } }); return new Map([...mapCopy1, ...mapCopy2]); }; const map1 = new Map([ ["key1", 1], ["key2", 2] ]); const map2 = new Map([ ["key2", 3], ["key4", 4] ]); const show = (object) => { return JSON.stringify(Array.from(object), null, 2) } document.getElementById("app").innerHTML = ` <h1>Maps are awesome!</h1> <div>map1 = ${show(map1)}</div> <div>map2 = ${show(map2)}</div><br> <div>Set value of last duplicate key:<br>merged map = ${show(mergeMaps(map1, map2))}</div><br> <div>Set value of pair-wise summated duplicate keys:<br>merged map = ${show(mergeMaps(map1, map2, (value1, value2) => value1 + value2))}</div><br> <div>Set value of pair-wise difference of duplicate keys:<br>merged map = ${show(mergeMaps(map1, map2, (value1, value2) => value1 - value2))}</div><br> <div>Set value of pair-wise multiplication of duplicate keys:<br>merged map = ${show(mergeMaps(map1, map2, (value1, value2) => value1 * value2))}</div><br> <div>Set value of pair-wise quotient of duplicate keys:<br>merged map = ${show(mergeMaps(map1, map2, (value1, value2) => value1 / value2))}</div><br> <div>Set value of pair-wise power of duplicate keys:<br>merged map = ${show(mergeMaps(map1, map2, (value1, value2) => Math.pow(value1, value2)))}</div><br> `; <!DOCTYPE html> <html> <head> <title>Parcel Sandbox</title> <meta charset="UTF-8" /> </head> <body> <div id="app"></div> <script src="src/index.js"> </script> </body> </html>

不,它们没有内置操作,但你可以很容易地创建自己的操作:

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;
};

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

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' ]