Convert an array of objects with a unique id property to a Map

前端 未结 3 1775
隐瞒了意图╮
隐瞒了意图╮ 2021-01-18 17:51

I have an array of objects, where each object has a unique member called id. How do I create a Map where the id if the Map\'s key?

3条回答
  •  孤街浪徒
    2021-01-18 18:04

    You can use Array.prototype.map() to map the array elements to [element.id, element] pairs and then pass the resulting array to the Map constructor.

    const arr = [{id: 1, a: true, b: false}, {id: 2, a: false, b: true}]
    
    const map = new Map(arr.map(element => [element.id, element]))
    
    // Check if map looks OK
    for (const [key, value] of map) {
      console.log(key, value)
    }

提交回复
热议问题