[英]Array.groupBy in Typescript e6 can be use with arrow function
我正在尝试将一种方法转换为通用方法以与 JavaScript 中的箭头函数一起使用,但不知何故无法确定我应该如何转换它。 groupBy: <Map>(predicate: (item: T) => Map[]) => Map[];
Array.prototype.groupBy = function (predicate) {
return this.reduce(
(entryMap, e) => entryMap.set(e.status, [...entryMap.get(e.status) || [], e]),
new Map()
)};
我在这个方法中收到的谓词就像ƒ (x) { return x.status; }
ƒ (x) { return x.status; }
.
我想将此e.status
替换为一些通用的,这样我就可以像arrayData.groupBy(x=>x.status)
一样使用它。 作为初学者,我无法弄清楚我应该如何做到这一点。 我在@Arthur Tacca 发布的帖子@ https://stackoverflow.com/a/47752730/5001462 中找到了方法
提前致谢
链接问题中的代码根据e.status
对对象进行e.status
。 但是,在您的情况下,该属性是动态的。 如果你通过x => x.status
作谓语的说法,你怎么弄的e.status
每个对象中reduce
? 您只需要使用e
参数调用predicate
。 因此,将所有e.status
替换为predicate(e)
Array.prototype.groupBy = function(predicate) { return this.reduce( (entryMap, e) => entryMap.set(predicate(e), [...entryMap.get(predicate(e)) || [], e]), new Map() ) }; const arr = [{ status: 10, id: 1 }, { status: 10, id: 2 }, { status:20, id: 3 }], map = arr.groupBy(e => e.status) console.log(map.get(10)) console.log(map.get(20)) console.log(map.get(30))
请注意,扩展本机对象是一种不好的做法。 即使您向原型添加新项目,也要确保使用Object.defineProperty
进行添加,如下所示:
Object.defineProperty(Array.prototype, "groupBy", {
value: function(predicate) {
return this.reduce(
(entryMap, e) => entryMap.set(predicate(e), [...entryMap.get(predicate(e)) || [], e]),
new Map()
)
},
configurable: true,
writable: true
});
如果您以这种方式定义它, enumerable
将被设置为false
。 如果直接添加Array.prototype.groupBy = function(predicate){}
, enumerable
将设置为true
,它将显示在for..in
循环中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.