0
# lodash.keyby
1
2
The lodash method `keyBy` exported as a standalone module. Creates an object composed of keys generated from the results of running each element of a collection through an iteratee function. The corresponding value of each key is the last element responsible for generating the key.
3
4
## Package Information
5
6
- **Package Name**: lodash.keyby
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install lodash.keyby`
10
11
## Core Imports
12
13
```javascript
14
var keyBy = require('lodash.keyby');
15
```
16
17
For ES modules (if supported by bundler):
18
19
```javascript
20
import keyBy from 'lodash.keyby';
21
```
22
23
## Basic Usage
24
25
```javascript
26
var keyBy = require('lodash.keyby');
27
28
var array = [
29
{ 'dir': 'left', 'code': 97 },
30
{ 'dir': 'right', 'code': 100 }
31
];
32
33
// Using function iteratee
34
keyBy(array, function(o) {
35
return String.fromCharCode(o.code);
36
});
37
// => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
38
39
// Using property string iteratee
40
keyBy(array, 'dir');
41
// => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
42
```
43
44
## Capabilities
45
46
### Object Key Generation
47
48
Creates an object where keys are generated from running each element through an iteratee function and values are the elements themselves. When multiple elements generate the same key, the last element wins.
49
50
```javascript { .api }
51
/**
52
* Creates an object composed of keys generated from the results of running
53
* each element of `collection` through `iteratee`. The corresponding value
54
* of each key is the last element responsible for generating the key.
55
*
56
* @param {Array|Object} collection The collection to iterate over.
57
* @param {Function|Object|string} [iteratee=_.identity] The iteratee to transform keys.
58
* @returns {Object} Returns the composed aggregate object.
59
*/
60
function keyBy(collection, iteratee);
61
```
62
63
**Parameters:**
64
65
- `collection` (Array|Object): The collection to iterate over. Can be an array of items or an object with enumerable properties.
66
- `iteratee` (Function|Object|string, optional): The iteratee to transform keys. Defaults to identity function if not provided.
67
68
**Returns:**
69
70
- `Object`: The composed aggregate object where keys are generated by the iteratee and values are the original elements.
71
72
**Iteratee Types:**
73
74
1. **Function**: Custom key generation function that receives the value and returns the key.
75
2. **String**: Property path to use as the key (supports nested properties with dot notation).
76
3. **Number**: Array index for arrays of arrays.
77
4. **Object**: Partial object for property matching (uses lodash's matches functionality).
78
5. **Undefined/null**: Uses identity function (element itself becomes the key).
79
80
**Usage Examples:**
81
82
**Function Iteratee:**
83
```javascript
84
var users = [
85
{ 'name': 'barney', 'age': 36 },
86
{ 'name': 'fred', 'age': 40 }
87
];
88
89
keyBy(users, function(user) {
90
return user.name.charAt(0);
91
});
92
// => { 'b': { 'name': 'barney', 'age': 36 }, 'f': { 'name': 'fred', 'age': 40 } }
93
```
94
95
**String Property Iteratee:**
96
```javascript
97
keyBy(users, 'name');
98
// => { 'barney': { 'name': 'barney', 'age': 36 }, 'fred': { 'name': 'fred', 'age': 40 } }
99
```
100
101
**Numeric Index Iteratee (Arrays of Arrays):**
102
```javascript
103
var pairs = [[1, 'a'], [2, 'b'], [1, 'c']];
104
keyBy(pairs, 0);
105
// => { '1': [1, 'c'], '2': [2, 'b'] }
106
107
keyBy(pairs, 1);
108
// => { 'a': [1, 'a'], 'b': [2, 'b'], 'c': [1, 'c'] }
109
```
110
111
**Object Collections:**
112
```javascript
113
var scores = { 'math': 95, 'english': 88, 'science': 92 };
114
keyBy(scores, function(score) {
115
return score >= 90 ? 'excellent' : 'good';
116
});
117
// => { 'excellent': 92, 'good': 88 }
118
```
119
120
**Handling Object.prototype Properties:**
121
```javascript
122
// Safely handles built-in properties
123
keyBy([6.1, 4.2, 6.3], function(n) {
124
return Math.floor(n) > 4 ? 'hasOwnProperty' : 'constructor';
125
});
126
// => { 'hasOwnProperty': 6.3, 'constructor': 4.2 }
127
```
128
129
**Key Collision Behavior:**
130
```javascript
131
var data = [
132
{ id: 1, category: 'A' },
133
{ id: 2, category: 'B' },
134
{ id: 3, category: 'A' } // This will overwrite first element
135
];
136
137
keyBy(data, 'category');
138
// => { 'A': { id: 3, category: 'A' }, 'B': { id: 2, category: 'B' } }
139
```
140
141
**Edge Cases:**
142
143
- **Empty Collections**: Returns empty object `{}`
144
- **Null/Undefined Values**: Safely handled, uses string conversion for keys
145
- **Key Collisions**: Last element with duplicate key wins
146
- **Non-enumerable Properties**: Only enumerable properties are processed for object collections
147
- **Built-in Property Names**: Safely handles property names like 'constructor', 'hasOwnProperty', '__proto__'
148
149
**Compatibility:**
150
151
- **Node.js**: All versions
152
- **Browsers**: All modern browsers (uses ES5 features)
153
- **TypeScript**: Type definitions available via `@types/lodash.keyby`
154
- **Bundle Size**: Lightweight standalone module optimized for tree-shaking