Ecmascript 6 下划线'的ES6版本;s_uxby()
下划线有一个整洁的函数Ecmascript 6 下划线'的ES6版本;s_uxby(),ecmascript-6,underscore.js,Ecmascript 6,Underscore.js,下划线有一个整洁的函数indexBy,用于映射某个键上的数组。从文件中: _.indexBy(列表、迭代对象、上下文) 给定一个列表和一个iteratee函数,该函数为列表中的每个元素(或属性名)返回一个键,然后返回一个对象,其中包含每个项的索引。就像groupBy一样,但当您知道自己的密钥是唯一的时 使用示例: var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
indexBy
,用于映射某个键上的数组。从文件中:
_.indexBy(列表、迭代对象、上下文)
给定一个列表和一个iteratee函数,该函数为列表中的每个元素(或属性名)返回一个键,然后返回一个对象,其中包含每个项的索引。就像groupBy一样,但当您知道自己的密钥是唯一的时
使用示例:
var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.indexBy(stooges, 'age');
=> {
"40": {name: 'moe', age: 40},
"50": {name: 'larry', age: 50},
"60": {name: 'curly', age: 60}
}
没有库,如何在纯ES6中编写此函数?此函数通过
迭代对象和上下文实现.indexBy
的完整定义:
function indexBy(list, iteratee, context) {
return list.reduce((map, obj) => {
const key = typeof iteratee === 'string' ? obj[iteratee] : iteratee.call(context, obj);
map[key] = obj;
return map;
}, {});
}