[英]Lodash chaining with sortBy produces error while vanilla sort works
鉴于这种:
let nums = [1,5,4]
let sorter = (a,b) => a.property > b.property ? 1 : -1;
let mapper = x => {return {property:x}}
这将引发错误:
_.chain(nums).map(mapper).sortBy(sorter).value()
// Uncaught TypeError: Cannot read property 'property' of undefined
虽然这不是:
nums.map(mapper).sort(sorter)
// [{"property":1},{"property":4},{"property":5}]
是什么赋予了? 我们不能保证sortBy
将在map
之后运行吗? 还是我在这里错过了真正明显的东西?
Lodash的sortBy
函数接受迭代进行排序的第二个参数,并且不接受与本机sort()
函数相同的排序函数模式。 您可以只在要排序的键的字符串中放置:
_.chain(nums).map(mapper).sortBy('property').value()
或传入一个指向要排序的属性的函数:
_.chain(nums).map(mapper).sortBy((o) => o.property).value()
lodash的sorter函数仅具有一个参数: https ://lodash.com/docs/4.17.4#sortBy
https://jsfiddle.net/jq26573q/
let sorter = (o) => o.property;
尽管更好的方法是直接指定属性:
let sorter = 'property';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.