Simplest way to merge ES6 Maps/Sets?

前端 未结 13 1207
广开言路
广开言路 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条回答
  • 2020-11-29 18:12

    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']
    
    0 讨论(0)
提交回复
热议问题