-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmake_tree.go
More file actions
59 lines (50 loc) · 1.03 KB
/
make_tree.go
File metadata and controls
59 lines (50 loc) · 1.03 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package go_utils
type TreeConfig struct {
ID string
PID string
Children string
}
type MakeTree interface {
construct([]map[string]interface{}) []map[string]interface{}
}
func (c *TreeConfig) GenerateTree(nodes []map[string]interface{}) []map[string]interface{} {
idMap := make(map[interface{}]interface{})
jsonTree := make([]map[string]interface{}, 0)
var id, pid, children string
if c.ID != "" {
id = c.ID
} else {
id = "id"
}
if c.PID != "" {
pid = c.PID
} else {
pid = "pid"
}
if c.Children != "" {
children = c.Children
} else {
children = "children"
}
for _, node := range nodes {
for k, v := range node {
if k == id {
value, ok := v.(interface{})
if ok {
idMap[value] = node
}
}
}
}
for _, node := range nodes {
pid, _ := node[pid].(interface{})
parent, ok := idMap[pid].(map[string]interface{})
if ok {
p, _ := parent[children].([]map[string]interface{})
parent[children] = append(p, node)
} else {
jsonTree = append(jsonTree, node)
}
}
return jsonTree
}