get.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. var staticHGKeyRE = require('./staticHGKeyRE')
  2. var helperGetHGSKeys = require('./helperGetHGSKeys')
  3. var hasOwnProp = require('./hasOwnProp')
  4. var isUndefined = require('./isUndefined')
  5. var eqNull = require('./eqNull')
  6. /**
  7. * 获取对象的属性的值,如果值为 undefined,则返回默认值
  8. * @param {Object/Array} obj 对象
  9. * @param {String/Function} property 键、路径
  10. * @param {Object} defaultValue 默认值
  11. * @return {Object}
  12. */
  13. function get (obj, property, defaultValue) {
  14. if (eqNull(obj)) {
  15. return defaultValue
  16. }
  17. var result = getValueByPath(obj, property)
  18. return isUndefined(result) ? defaultValue : result
  19. }
  20. function getDeepProps (obj, key) {
  21. var matchs = key ? key.match(staticHGKeyRE) : ''
  22. return matchs ? (matchs[1] ? (obj[matchs[1]] ? obj[matchs[1]][matchs[2]] : undefined) : obj[matchs[2]]) : obj[key]
  23. }
  24. function getValueByPath (obj, property) {
  25. if (obj) {
  26. var rest, props, len
  27. var index = 0
  28. if (obj[property] || hasOwnProp(obj, property)) {
  29. return obj[property]
  30. } else {
  31. props = helperGetHGSKeys(property)
  32. len = props.length
  33. if (len) {
  34. for (rest = obj; index < len; index++) {
  35. rest = getDeepProps(rest, props[index])
  36. if (eqNull(rest)) {
  37. if (index === len - 1) {
  38. return rest
  39. }
  40. return
  41. }
  42. }
  43. }
  44. return rest
  45. }
  46. }
  47. }
  48. module.exports = get