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

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

    You could map a new array in the needed format for the Map.

    var array = [{ id: 1, value: 'one' }, { id: 2, value: 'two' }, { id: 3, value: 'three' }, { id: 4, value: 'four' }, { id: 5, value: 'five' }],
        map = new Map(array.map(a => [a.id, a]));
    
    console.log([...map]);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    Or iterate and add the new item to a certain key

    var array = [{ id: 1, value: 'one' }, { id: 2, value: 'two' }, { id: 3, value: 'three' }, { id: 4, value: 'four' }, { id: 5, value: 'five' }],
        map = new Map();
    
    array.forEach(a => map.set(a.id, a));
    console.log([...map]);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题