将具有唯一id属性的对象数组转换为Map [英] Convert an array of objects with a unique id property to a Map
本文介绍了将具有唯一id属性的对象数组转换为Map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个对象数组,其中每个对象都有一个称为id
的唯一成员.如何在id
(如果地图的密钥)所在的位置创建地图?
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?
推荐答案
您想将数组简化为地图:
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));
此处是 JSPref ,反对使用map
和forEach
.
Here is a JSPref against using map
and forEach
.
在Chrome v53中,reduce
是最快的,然后是forEach
,而map
是最慢的.
In Chrome v53 reduce
is fastest, then forEach
with map
being the slowest.
这篇关于将具有唯一id属性的对象数组转换为Map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文