-
Notifications
You must be signed in to change notification settings - Fork 24
/
flatten.go
32 lines (29 loc) · 695 Bytes
/
flatten.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package ffmt
import (
"strconv"
"strings"
)
func Flatten(nested map[string]interface{}) map[string]interface{} {
if nested == nil {
return nested
}
flatmap := map[string]interface{}{}
var prefixes []string
flatten(0, flatmap, nested, prefixes)
return flatmap
}
func flatten(deep int, flatMap map[string]interface{}, nested interface{}, prefixes []string) {
switch t := nested.(type) {
case map[string]interface{}:
for k, v := range t {
flatten(deep+1, flatMap, v, append(prefixes, k))
}
case []interface{}:
for i, v := range t {
flatten(deep+1, flatMap, v, append(prefixes, strconv.Itoa(i)))
}
default:
key := strings.Join(prefixes, ".")
flatMap[key] = t
}
}