I have a map which has as value an array of maps.
Example:
thisMap["coins"][0] = aMap["random":"something"]
thisMap["notes"][1] = aMap["not-random":"something else"]
thisMap["coins"][2] = aMap["not-random":"something else"]
I can't figure it out how to do this as go
seems to allow setting data only at one level when you deal with maps [name][value] = value
.
So far I have this code which fails
package main
func main() {
something := []string{"coins", "notes", "gold?", "coins", "notes"}
thisMap := make(map[string][]map[string]int)
for k, v := range something {
aMap := map[string]string{
"random": "something",
}
thisMap[v] = [k]aMap
}
}
Edit: The slice values ("coins", "notes" etc ) can repeat so this is the reason why I need use an index []
.
. map() can be used to iterate through objects in an array and, in a similar fashion to traditional arrays, modify the content of each individual object and return a new array. This modification is done based on what is returned in the callback function.
Working example (click to play):
something := []string{"coins", "notes", "gold?"}
thisMap := make(map[string][]map[string]int)
for _, v := range something {
aMap := map[string]int{
"random": 12,
}
thisMap[v] = append(thisMap[v], aMap)
}
When iterating over the newly created thisMap
, you need to make room for the new value aMap
. The builtin function append
does that for you when using slices. It makes room and appends the value to the slice.
If you're using more complex data types that can't be initialized as easily as slices, you first have to check if the key is already in the map and, if it is not, initialize your data type. Checking for map elements is documented here. Example with maps (click to play):
thisMap := make(map[string]map[string]int)
for _, v := range something {
if _, ok := thisMap[v]; !ok {
thisMap[v] = make(map[string]int)
}
thisMap[v]["random"] = 12
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With