Simplest way to merge ES6 Maps/Sets?

前端 未结 13 1244
广开言路
广开言路 2020-11-29 17:24

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

13条回答
  •  萌比男神i
    2020-11-29 18:07

    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

    function concatSets(set, ...iterables) {
        for (const iterable of iterables) {
            for (const item of iterable) {
                set.add(item);
            }
        }
    }
    

    Usage:

    const setA = new Set([1, 2, 3]);
    const setB = new Set([4, 5, 6]);
    const setC = new Set([7, 8, 9]);
    concatSets(setA, setB, setC);
    // setA will have items 1, 2, 3, 4, 5, 6, 7, 8, 9
    

    Map

    function concatMaps(map, ...iterables) {
        for (const iterable of iterables) {
            for (const item of iterable) {
                map.set(...item);
            }
        }
    }
    

    Usage:

    const mapA = new Map().set('S', 1).set('P', 2);
    const mapB = new Map().set('Q', 3).set('R', 4);
    concatMaps(mapA, mapB);
    // mapA will have items ['S', 1], ['P', 2], ['Q', 3], ['R', 4]
    

提交回复
热议问题