I have a list of objects with this definition:
type MyObject struct {
ID int `json:"id"`
Level int `json:"level"`
CityID int `json:"city_id"`
}
I want to categorize them based on CityID
in order to get a list of lists where each inner list's items have the same CityID
.
For example, if I have the following list:
[
MyObject {ID: 1, Level: 12, CityID: 7},
MyObject {ID: 2, Level: 15, CityID: 2},
MyObject {ID: 3, Level: 55, CityID: 4},
MyObject {ID: 4, Level: 88, CityID: 7},
MyObject {ID: 5, Level: 11, CityID: 4},
MyObject {ID: 6, Level: 5, CityID: 7},
MyObject {ID: 7, Level: 42, CityID: 2}
]
I need below output:
[
[MyObject {ID: 1, Level: 12, CityID: 7}, MyObject {ID: 4, Level: 88, CityID: 7}, MyObject {ID: 6, Level: 5, CityID: 7}],
[MyObject {ID: 2, Level: 15, CityID: 2}, MyObject {ID: 7, Level: 42, CityID: 2}],
[MyObject {ID: 3, Level: 55, CityID: 4}, MyObject {ID: 5, Level: 11, CityID: 4}]
]
I know it is possible in python using itertools
, but I'm new in go
and have little knowledge about its libraries. Any help?
EDIT 1:
I am currently using this:
m := make(map[int][]MyObject)
for _, item := range myList {
if val, ok := m[item.CityID]; ok {
m[item.CityID] = append(val, item)
} else {
m[item.CityID] = []MyObject{item, }
}
}