forked from angus-c/just
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
29 lines (26 loc) · 739 Bytes
/
Copy pathindex.js
File metadata and controls
29 lines (26 loc) · 739 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
module.exports = index;
/*
index([{id: 'first', val: 1}, {id: 'second', val: 2}], 'id');
// {first: {id: 'first', val: 1}, second: {id: 'second', val: 2}}
index([{id: 'first', val: 1}, null], 'id'); // {first: {id: 'first', val: 1}}
index([], 'id'); // {}
index([], null); // throws
index({}, 'id'); // throws
*/
function index(arr, key) {
if (!Array.isArray(arr)) {
throw new Error('expected an array for first argument');
}
if (typeof key != 'string') {
throw new Error('expected a string for second argument');
}
var result = {};
var len = arr.length;
for (var i = 0; i < len; i++) {
var index = arr[i] && arr[i][key];
if (index) {
result[index] = arr[i];
}
}
return result;
}