has.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. var staticHGKeyRE = require('./staticHGKeyRE')
  2. var helperGetHGSKeys = require('./helperGetHGSKeys')
  3. var hasOwnProp = require('./hasOwnProp')
  4. /**
  5. * 检查键、路径是否是该对象的属性
  6. *
  7. * @param {Object/Array} data 对象
  8. * @param {String/Function} property 键、路径
  9. * @return {Boolean}
  10. */
  11. function has (obj, property) {
  12. if (obj) {
  13. if (hasOwnProp(obj, property)) {
  14. return true
  15. } else {
  16. var prop, arrIndex, objProp, matchs, rest, isHas
  17. var props = helperGetHGSKeys(property)
  18. var index = 0
  19. var len = props.length
  20. for (rest = obj; index < len; index++) {
  21. isHas = false
  22. prop = props[index]
  23. matchs = prop ? prop.match(staticHGKeyRE) : ''
  24. if (matchs) {
  25. arrIndex = matchs[1]
  26. objProp = matchs[2]
  27. if (arrIndex) {
  28. if (rest[arrIndex]) {
  29. if (hasOwnProp(rest[arrIndex], objProp)) {
  30. isHas = true
  31. rest = rest[arrIndex][objProp]
  32. }
  33. }
  34. } else {
  35. if (hasOwnProp(rest, objProp)) {
  36. isHas = true
  37. rest = rest[objProp]
  38. }
  39. }
  40. } else {
  41. if (hasOwnProp(rest, prop)) {
  42. isHas = true
  43. rest = rest[prop]
  44. }
  45. }
  46. if (isHas) {
  47. if (index === len - 1) {
  48. return true
  49. }
  50. } else {
  51. break
  52. }
  53. }
  54. }
  55. }
  56. return false
  57. }
  58. module.exports = has