我想要这样的东西:
let myMap = new Map<string, any>();
myMap.set("aaa", {a: 1, b: 2, c:3});
myMap.set("bbb", {a: 1, b: 2, c:6});
myMap.set("ccc", {a: 1, b: 2, c:9});
let cs = myMap.values().map(x => x.c);
从地图的所有条目中选择c属性。这是失败的:
Property 'map' does not exist on type 'IterableIterator<any>'.
对此有什么优雅的解决方案?
答案 0 :(得分:3)
您可以使用Array.from()
将所有可迭代对象转换为数组:
let myMap = new Map();
myMap.set("aaa", {a: 1, b: 2, c:3});
myMap.set("bbb", {a: 1, b: 2, c:6});
myMap.set("ccc", {a: 1, b: 2, c:9});
// Basic example
let cs = Array.from( myMap.values() ).map(x => x.c);
console.log( cs );
// Array.from also takes a mapping function as the second parameter, so even shorter:
let cs_alt = Array.from( myMap.values(), x => x.c );
console.log( cs_alt );