[英]Set a ES6 Map from an array of objects in Typescript?
I have an array of objects like such...我有一系列像这样的对象......
const myObjects: MyObjects[] = [{id: 1, data: "blah"}, {id: 2, data: "foo"}, {id: 3, data: "bar"}];
I want to set this data into a Map based on id.我想根据 id 将此数据设置为Map 。
The way I have now is a forEach
loop, but is there a simpler way or a method I am missing on the Map
type ?我现在的方法是forEach
循环,但是我在Map
类型上缺少一种更简单的方法或方法吗? I find myself doing this over and over again and thinking must be a simpler way.我发现自己一遍又一遍地这样做,并且认为必须是一种更简单的方法。
ie IE
const myMap = new Map<number, MyObject>();
myObjects.forEach(obj => {
myMap.set(obj.id, obj);
});
I want to move them to a Map
so they are easier to access by id versus iterating over the whole array.我想将它们移动到Map
以便它们更容易通过 id 访问而不是遍历整个数组。
Is there a simpler way or a method I am missing on the Map type?我在 Map 类型上缺少更简单的方法或方法吗?
"Simple" is a bit subjective. “简单”有点主观。 I usually use this approach because it fits in one line and because initializing a Map
with some elements might be faster than initializing it and then adding elements.我通常使用这种方法,因为它适合在一行中,并且因为使用某些元素初始化Map
可能比初始化它然后添加元素更快。
const myObjects: { id: number; data: string; }[] = [{id: 1, data: "blah"}, {id: 2, data: "foo"}, {id: 3, data: "bar"}];
const myMap = new Map(myObjects.map(obj => [obj.id, obj]));
Explanation: The Map
constructor takes an itrerable of iterables (in this case an array of arrays) as the first parameter.说明: Map
构造函数将一个可迭代对象(在本例中为数组数组)作为第一个参数。 Each element in the main array is an entry in the map, with the key being the element's first element and the value being the element's second element.主数组中的每个元素都是映射中的一个条目,键是元素的第一个元素,值是元素的第二个元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.