object.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. exports.set = function (target, path, value) {
  2. const fields = path.split('.')
  3. let obj = target
  4. const l = fields.length
  5. for (let i = 0; i < l - 1; i++) {
  6. const key = fields[i]
  7. if (!obj[key]) {
  8. obj[key] = {}
  9. }
  10. obj = obj[key]
  11. }
  12. obj[fields[l - 1]] = value
  13. }
  14. exports.get = function (target, path) {
  15. const fields = path.split('.')
  16. let obj = target
  17. const l = fields.length
  18. for (let i = 0; i < l - 1; i++) {
  19. const key = fields[i]
  20. if (!obj[key]) {
  21. return undefined
  22. }
  23. obj = obj[key]
  24. }
  25. return obj[fields[l - 1]]
  26. }
  27. exports.unset = function (target, path) {
  28. const fields = path.split('.')
  29. let obj = target
  30. const l = fields.length
  31. const objs = []
  32. for (let i = 0; i < l - 1; i++) {
  33. const key = fields[i]
  34. if (!obj[key]) {
  35. return
  36. }
  37. objs.unshift({ parent: obj, key, value: obj[key] })
  38. obj = obj[key]
  39. }
  40. delete obj[fields[l - 1]]
  41. // Clear empty objects
  42. for (const { parent, key, value } of objs) {
  43. if (!Object.keys(value).length) {
  44. delete parent[key]
  45. }
  46. }
  47. }