Guest User

Untitled

a guest
Nov 18th, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. var _ = require('lodash'
  2. )
  3. function getValueFromPath(path, obj, val) {
  4. let key = path.shift('.')
  5. // check for bracket notation
  6. if (key.indexOf('[') > -1) {
  7. const match = key.match(/(\w+)\[(\d+)\]/)
  8. if (match !== null) {
  9. key = match[2]
  10. obj = obj[match[1]]
  11. }
  12. }
  13.  
  14. // Return the value if done, otherwise, keep going
  15. return path.length === 0 ? (val !== undefined ? obj[key] = val : obj[key]) : getValueFromPath(path, obj[key], val)
  16. }
  17.  
  18. function isLeaf(str) {
  19. return str.length === -1
  20. }
  21.  
  22. function getNodeValue(path, obj, separator){
  23. // console.log('will search for data on path', path, obj)
  24. if(!path.length) return obj
  25. return path.indexOf(separator) > 0 ? _.find(obj[path.split(separator)[0]], { id: path.split(separator)[1] }) : obj[path]
  26. }
  27.  
  28. function getValueSafe(path, obj, sep) {
  29. if (!sep) sep = path.indexOf('|') === -1 ? ':' : '|'
  30. try {
  31. const [p1, ...p2] = path.split('.')
  32. obj = getNodeValue(p1, obj, sep)
  33. const remainder = p2.join('')
  34. // console.log('new obj & remainder', obj, remainder)
  35. return remainder.indexOf('.') !== -1 ? getValueSafe(remainder, obj, sep) : getNodeValue(remainder, obj, sep)
  36. } catch (e) {
  37. console.log(e)
  38. throw new Error('Path may contain an invalid ID.')
  39. }
  40. }
  41.  
  42.  
  43. const foo = {
  44. prop: "foo",
  45. content: [
  46. {
  47. id: "aaa",
  48. obtainFromMunicipality: [
  49. {
  50. id: "bbb"
  51. },
  52. {
  53. id: "ccc"
  54. }
  55. ]
  56. }
  57. ]
  58. }
  59.  
  60. console.log(getValueSafe('content:aaa', foo))
  61. console.log(getValueSafe('content:aaa.obtainFromMunicipality', foo))
  62. console.log(getValueSafe('content:aaa.obtainFromMunicipality:ccc', foo))
Add Comment
Please, Sign In to add comment