remove.go raw

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