toLookup.js 673 B

12345678910111213141516171819202122232425262728
  1. var isFunction = require('../lang/isFunction');
  2. /**
  3. * Creates an object that holds a lookup for the objects in the array.
  4. */
  5. function toLookup(arr, key) {
  6. var result = {};
  7. if (arr == null) {
  8. return result;
  9. }
  10. var i = -1, len = arr.length, value;
  11. if (isFunction(key)) {
  12. while (++i < len) {
  13. value = arr[i];
  14. result[key(value)] = value;
  15. }
  16. } else {
  17. while (++i < len) {
  18. value = arr[i];
  19. result[value[key]] = value;
  20. }
  21. }
  22. return result;
  23. }
  24. module.exports = toLookup;