支持提取每一项Item的指定字段作为list返回

This commit is contained in:
白茶清欢 2024-10-13 19:23:20 +08:00
parent ef80c6cb79
commit f3f064d064

View File

@ -10,6 +10,7 @@ package wrapper
import ( import (
"encoding/json" "encoding/json"
"git.zhangdeman.cn/zhangdeman/op_type" "git.zhangdeman.cn/zhangdeman/op_type"
"github.com/tidwall/gjson"
"reflect" "reflect"
"strings" "strings"
) )
@ -142,3 +143,24 @@ func (at *Array[Bt]) ToStringWithSplit(split string) StringResult {
Err: nil, Err: nil,
} }
} }
// ExtraField 提取[]map/[]struct 中的指定字段, 并以list形式返回
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 19:00 2024/10/13
func (at *Array[Bt]) ExtraField(fieldName string) *Array[any] {
if at.IsNil() {
return ArrayType[any]([]any{})
}
byteData, _ := json.Marshal(at.value)
res := make([]any, 0)
list := gjson.ParseBytes(byteData).Array()
for _, item := range list {
itemValue := item.Get(fieldName)
if itemValue.Exists() {
res = append(res, itemValue.Value())
}
}
return ArrayType(res)
}