美文网首页
对象数组选择字段升降序排序

对象数组选择字段升降序排序

作者: funcx | 来源:发表于2019-09-29 16:46 被阅读0次
    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
    }
    

    相关文章

      网友评论

          本文标题:对象数组选择字段升降序排序

          本文链接:https://www.haomeiwen.com/subject/mbvqyctx.html