mutations.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package objx
  2. // Exclude returns a new Map with the keys in the specified []string
  3. // excluded.
  4. func (d Map) Exclude(exclude []string) Map {
  5. excluded := make(Map)
  6. for k, v := range d {
  7. var shouldInclude bool = true
  8. for _, toExclude := range exclude {
  9. if k == toExclude {
  10. shouldInclude = false
  11. break
  12. }
  13. }
  14. if shouldInclude {
  15. excluded[k] = v
  16. }
  17. }
  18. return excluded
  19. }
  20. // Copy creates a shallow copy of the Obj.
  21. func (m Map) Copy() Map {
  22. copied := make(map[string]interface{})
  23. for k, v := range m {
  24. copied[k] = v
  25. }
  26. return New(copied)
  27. }
  28. // Merge blends the specified map with a copy of this map and returns the result.
  29. //
  30. // Keys that appear in both will be selected from the specified map.
  31. // This method requires that the wrapped object be a map[string]interface{}
  32. func (m Map) Merge(merge Map) Map {
  33. return m.Copy().MergeHere(merge)
  34. }
  35. // Merge blends the specified map with this map and returns the current map.
  36. //
  37. // Keys that appear in both will be selected from the specified map. The original map
  38. // will be modified. This method requires that
  39. // the wrapped object be a map[string]interface{}
  40. func (m Map) MergeHere(merge Map) Map {
  41. for k, v := range merge {
  42. m[k] = v
  43. }
  44. return m
  45. }
  46. // Transform builds a new Obj giving the transformer a chance
  47. // to change the keys and values as it goes. This method requires that
  48. // the wrapped object be a map[string]interface{}
  49. func (m Map) Transform(transformer func(key string, value interface{}) (string, interface{})) Map {
  50. newMap := make(map[string]interface{})
  51. for k, v := range m {
  52. modifiedKey, modifiedVal := transformer(k, v)
  53. newMap[modifiedKey] = modifiedVal
  54. }
  55. return New(newMap)
  56. }
  57. // TransformKeys builds a new map using the specified key mapping.
  58. //
  59. // Unspecified keys will be unaltered.
  60. // This method requires that the wrapped object be a map[string]interface{}
  61. func (m Map) TransformKeys(mapping map[string]string) Map {
  62. return m.Transform(func(key string, value interface{}) (string, interface{}) {
  63. if newKey, ok := mapping[key]; ok {
  64. return newKey, value
  65. }
  66. return key, value
  67. })
  68. }