bbo
Version:
bbo is a utility library of zero dependencies for javascript.
34 lines (25 loc) • 636 B
JavaScript
;
require('./get_tag.js');
var is_array = require('./is_array.js');
var is_string = require('./is_string.js');
/**
* return an object from an array, keyed by the value at the given id
*/
function indexBy(arr, key) {
if (!is_array(arr)) {
throw new Error('expected an array for first argument');
}
if (!is_string(key)) {
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;
}
module.exports = indexBy;