2024-12-30 16:34:26 +08:00

41 lines
975 B
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package utils
import "sort"
// SortMapParams 对map的key进行排序包括多层嵌套的情况
func SortMapParams(data map[string]interface{}) map[string]interface{} {
sortedMap := make(map[string]interface{})
keys := make([]string, 0, len(data))
// 收集所有的key
for key := range data {
keys = append(keys, key)
}
// 对key进行排序
sort.Strings(keys)
// 通过排序后的key插入新map中
for _, key := range keys {
value := data[key]
switch valueTyped := value.(type) {
case map[string]interface{}:
// 如果是嵌套的map递归调用
sortedMap[key] = SortMapParams(valueTyped)
case []interface{}:
// 如果是嵌套的slice对其中的map进行递归调用
for i, v := range valueTyped {
if vMap, ok := v.(map[string]interface{}); ok {
valueTyped[i] = SortMapParams(vMap)
}
}
sortedMap[key] = valueTyped
default:
// 否则直接插入
sortedMap[key] = value
}
}
return sortedMap
}