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

前端 未结 3 1776
隐瞒了意图╮
隐瞒了意图╮ 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:23

    You want to reduce your array into a map:

    const arr = [{id:1},{id:2},{id:2}];
    
    const map = arr.reduce((acc, item) => acc.set(item.id, item), new Map());
    
    console.log(map.get(1));

    Here is a JSPref against using map and forEach.

    In Chrome v53 reduce is fastest, then forEach with map being the slowest.

提交回复
热议问题