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

那年仲夏 提交于 2020-01-30 04:59:49

问题


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?


回答1:


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.




回答2:


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



回答3:


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; }


来源:https://stackoverflow.com/questions/40220313/convert-an-array-of-objects-with-a-unique-id-property-to-a-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!