object/path.js

  1. import curry from '../curry'
  2. /**
  3. * @function path
  4. * @desc Returns the value of a property identified by a number of nested key values
  5. * @param {Array} path - Array of key values
  6. * @param {Object|Array} An object or an array from which to retrieve the keys
  7. * @example
  8. *
  9. * let t = {
  10. * a: {
  11. * b : [0, 1]
  12. * },
  13. * b : 1
  14. * }
  15. *
  16. * const v = path(['a', 'b', 0], t)
  17. * v === 0
  18. */
  19. export default curry(function path (path, obj) {
  20. let val = obj
  21. let idx = 0
  22. let p
  23. while (idx < path.length) {
  24. if (val == null) {
  25. return
  26. }
  27. p = path[idx]
  28. val = Number.isInteger(p)
  29. ? p < 0 ? val[val.length + p] : val[p]
  30. : val[p]
  31. idx += 1
  32. }
  33. return val
  34. })