Skip to content

Commit 4f03050

Browse files
authored
Add flatten-keys functionality to mapstr (#45)
1 parent fa32991 commit 4f03050

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

mapstr/mapstr.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -295,6 +295,37 @@ func flatten(prefix string, in, out M) M {
295295
return out
296296
}
297297

298+
// FlattenKeys flattens given MapStr keys and returns a containing array pointer
299+
//
300+
// Example:
301+
// "hello": MapStr{"world": "test" }
302+
//
303+
// This is converted to:
304+
// ["hello.world"]
305+
func (m M) FlattenKeys() *[]string {
306+
out := make([]string, 0)
307+
flattenKeys("", m, &out)
308+
309+
return &out
310+
}
311+
312+
func flattenKeys(prefix string, in M, out *[]string) {
313+
for k, v := range in {
314+
var fullKey string
315+
if prefix == "" {
316+
fullKey = k
317+
} else {
318+
fullKey = prefix + "." + k
319+
}
320+
321+
if m, ok := tryToMapStr(v); ok {
322+
flattenKeys(fullKey, m, out)
323+
}
324+
325+
*out = append(*out, fullKey)
326+
}
327+
}
328+
298329
// Union creates a new M containing the union of the
299330
// key-value pairs of the two maps. If the same key is present in
300331
// both, the key-value pairs from dict2 overwrite the ones from dict1.

mapstr/mapstr_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -853,6 +853,21 @@ func TestFlatten(t *testing.T) {
853853
}
854854
}
855855

856+
func TestFlattenKeys(t *testing.T) {
857+
expected := []string{"elastic.search.keys", "elastic.search", "elastic"}
858+
input := M{
859+
"elastic": M{
860+
"search": M{
861+
"keys": "value",
862+
},
863+
},
864+
}
865+
866+
result := input.FlattenKeys()
867+
868+
assert.Equal(t, &expected, result)
869+
}
870+
856871
func BenchmarkMapStrFlatten(b *testing.B) {
857872
m := M{
858873
"test": 15,

0 commit comments

Comments
 (0)