remove.go 765 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package mxj
  2. import "strings"
  3. // Removes the path.
  4. func (mv Map) Remove(path string) error {
  5. m := map[string]interface{}(mv)
  6. return remove(m, path)
  7. }
  8. func remove(m interface{}, path string) error {
  9. val, err := prevValueByPath(m, path)
  10. if err != nil {
  11. return err
  12. }
  13. lastKey := lastKey(path)
  14. delete(val, lastKey)
  15. return nil
  16. }
  17. // returns the last key of the path.
  18. // lastKey("a.b.c") would had returned "c"
  19. func lastKey(path string) string {
  20. keys := strings.Split(path, ".")
  21. key := keys[len(keys)-1]
  22. return key
  23. }
  24. // returns the path without the last key
  25. // parentPath("a.b.c") whould had returned "a.b"
  26. func parentPath(path string) string {
  27. keys := strings.Split(path, ".")
  28. parentPath := strings.Join(keys[0:len(keys)-1], ".")
  29. return parentPath
  30. }