将具有唯一id属性的对象数组转换为Map [英] Convert an array of objects with a unique id property to a Map

查看:274
本文介绍了将具有唯一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 ,反对使用mapforEach.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆