> For the complete documentation index, see [llms.txt](https://lodash.shujuwajue.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lodash.shujuwajue.com/collection/keyby.md). Agents can also search and read this documentation through its [MCP server](https://lodash.shujuwajue.com/~gitbook/mcp).

# \_.keyBy（遍历处理数组或对象元素值）

**语法：**

```javascript
_.keyBy(collection, [iteratee=_.identity])
```

**源代码链接：**[source](https://github.com/lodash/lodash/blob/4.17.10/lodash.js#L9506)

**npm包链接：**[npm package](https://www.npmjs.com/package/lodash.keyby)

**描述：**

创建一个对象组成， key（键） 是`collection`（集合）中的每个元素经过`iteratee`（迭代函数） 处理后返回的结果。 每个 key（键）对应的值是生成key（键）的最后一个元素。`iteratee`（迭代函数）调用1个参数：*(value)*。

**开始版本：**&#x34;.0.0

**参数：**

* `collection (Array|Object)`: 用来迭代的集合。
* `[iteratee=_.identity] (Array|Function|Object|string)`: 这个迭代函数用来转换key。

**返回值：**

* `(Object)`: 返回一个组成聚合的对象。

**例子：**

```javascript
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 } }
```
