主题
keyBy
js
_.keyBy(collection, [iteratee=_.identity])
创建一个由运行 collection
至 iteratee
的每个元素的结果生成的键组成的对象。每个键的对应值是负责生成键的最后一个元素。迭代器使用一个参数调用:(value)。
¥Creates an object composed of keys generated from the results of running each element of collection
thru iteratee
. The corresponding value of each key is the last element responsible for generating the key. The iteratee is invoked with one argument: (value).
新增于
¥Since
4.0.0
参数
¥Arguments
collection
(数组|对象):要迭代的集合。¥
collection
(Array|Object): The collection to iterate over.[iteratee=_.identity]
(函数):用于转换键的迭代器。¥
[iteratee=_.identity]
(Function): The iteratee to transform keys.
返回
¥Returns
(对象):返回组合的聚合对象。
¥(Object): Returns the composed aggregate object.
示例
¥Example
js
var array = [
{ 'dir': 'left', 'code': 97 },
{ 'dir': 'right', 'code': 100 }
];
_.keyBy(array, function(o) {
return String.fromCharCode(o.code);
});
// => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
_.keyBy(array, 'dir');
// => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }