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


当前回答

例子

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

其他回答

根据Asaf Katz的回答,以下是一个打字版本:

export function union<T> (...iterables: Array<Set<T>>): Set<T> {
  const set = new Set<T>()
  iterables.forEach(iterable => {
    iterable.forEach(item => set.add(item))
  })
  return set
}

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

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

你可以使用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}

我已经创建了一个小片段,使用ES6中的一个函数合并任意数量的set。你可以改变“设置”为“地图”,让它与地图一起工作。

const mergeSets = (...args) => {
    return new Set(args.reduce((acc, current) => {
        return [...acc, ...current];
    }, []));
};

const foo = new Set([1, 2, 3]);
const bar = new Set([1, 3, 4, 5]);

mergeSets(foo, bar); // Set(5) {1, 2, 3, 4, 5}
mergeSets(foo, bar, new Set([6])); // Set(6) {1, 2, 3, 4, 5, 6}

我创建了一个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>