Home > Back-end >  Find an item in array of maps and delete it
Find an item in array of maps and delete it

Time:10-27

I have an array of maps, from which I want to delete an element if it exists, which is determined by its "key".

How to do it? I want it not to be slow. Preserving the order isn't important.

myMaps = []map[string]interface{} {
  map[string]interface{} {"key": "aaa", "key2": 222, "key3": "aafdsafd"},
  map[string]interface{} {"key": "key_to_delete", "key2": 366, "key3": "333aafdsafd"},
  map[string]interface{} {"key": "cccc", "key2": 467, "key3": "jhgfjhg"}, 
}
for _, x := range myMaps {
  if x["key"] == "key_to_delete" {
    //delete this element as a) key of the map b) the map-element as an element of the array; How?
  }
}

The delete(...) function:

when iterating over an array, a copy of it is what gets passed in the body of a loop. No? How would then delete(...) delete an element from the real array?

update:

I need to know of how to delete 2 types of entities, and for my case:

  • an element of an array - a map
  • an element of a map, with a certain key

Without using a third-party library.

CodePudding user response:

If you want to delete the key from the map:

for _, x := range myMaps {
    if x["key"] == "key_to_delete" {
        delete(x, "key")
    }
}

If what you want is to delete the map from the array it gets complicated, you're better off creating a second array and inserting into it if the current map is to be kept:

myFilteredMaps := make([]map[string]interface{}, 0, len(myMaps))
for _, x := range myMaps {
    if x["key"] != "key_to_delete" {
        myFilteredMaps = append(myFilteredMaps, x)
    }
}
myMaps = myFilteredMaps

Both of these are pretty quick so long as len(myMaps) isn't too large, both have linear runtime with respect to that length.

  •  Tags:  
  • go
  • Related