Advertisement
Guest User

Untitled

a guest
Sep 24th, 2017
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.84 KB | None | 0 0
  1. /**
  2. * Returns the value at the given property.
  3. *
  4. * @param {object} - the input object
  5. * @param {string} - the property accessor expression.
  6. * @returns {*}
  7. * @alias module:object-get
  8. * @example
  9. * > objectGet({ animal: 'cow' }, 'animal')
  10. * 'cow'
  11. *
  12. * > objectGet({ animal: { mood: 'lazy' } }, 'animal')
  13. * { mood: 'lazy' }
  14. *
  15. * > objectGet({ animal: { mood: 'lazy' } }, 'animal.mood')
  16. * 'lazy'
  17. *
  18. * > objectGet({ animal: { mood: 'lazy' } }, 'animal.email')
  19. * undefined
  20. */
  21. function object_get(object, expression) {
  22. if (!(object && expression)) throw new Error('both object and expression args are required')
  23. return (''+expression).trim().split('.').reduce(function (prev, curr) {
  24. var arr = curr.match(/(.*?)\[(.*?)\]/)
  25. if (arr) {
  26. return prev && prev[arr[1]][arr[2]]
  27. } else {
  28. return prev && prev[curr]
  29. }
  30. }, object);
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement