package main
import (
"encoding/json"
"log"
"sort"
)
func main() {
m := []map[string]interface{}{
{"a": 1, "b": 0, "c": 3},
{"a": 2, "b": 0, "c": 3},
{"a": 1, "b": 1, "c": 3},
{"a": 3, "b": 0, "c": 3},
{"a": 5, "b": 2, "c": 3},
}
log.Println(GetSortSlice(&m, "-a"))
}
func GetSortSlice(obj interface{}, str string) interface{} {
data, _ := json.Marshal(obj)
ms := []map[string]interface{}{}
json.Unmarshal(data, &ms)
sort.Slice(ms, func(i, j int) bool {
if str == "" {
return false
}
field := ""
asc := true
if str[:1] == "-" {
field = str[1:]
asc = false
} else {
field = str
}
v1, ok := ms[i][field].(float64)
if !ok {
v1 = 0
}
v2, ok := ms[j][field].(float64)
if !ok {
v2 = 0
}
if asc {
return v1 < v2
} else {
return v1 > v2
}
})
return ms
}
网友评论