82 lines
2.1 KiB
Go
82 lines
2.1 KiB
Go
|
package utils
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"gitea.24example.ru/spavelit/bpiek/model"
|
||
|
"strings"
|
||
|
)
|
||
|
|
||
|
func updateNested(d map[string]interface{}, keys []string, value map[string]interface{}) {
|
||
|
for _, key := range keys[:len(keys)-1] {
|
||
|
if _, exists := d[key]; !exists {
|
||
|
d[key] = map[string]interface{}{}
|
||
|
}
|
||
|
d = d[key].(map[string]interface{})
|
||
|
}
|
||
|
d[keys[len(keys)-1]] = value
|
||
|
}
|
||
|
|
||
|
func ConvertListToNestedDict(list []model.Category, tree map[string]interface{}) {
|
||
|
var tmpCategories []model.TreeCategories
|
||
|
for _, item := range list {
|
||
|
tmpCategories = append(tmpCategories, model.TreeCategories{
|
||
|
Name: item.Name,
|
||
|
Slug: item.Slug,
|
||
|
Url: item.Url,
|
||
|
Children: []model.TreeCategories{},
|
||
|
})
|
||
|
}
|
||
|
|
||
|
idx := 0
|
||
|
for idx < len(tmpCategories) {
|
||
|
category := tmpCategories[idx]
|
||
|
if category.Url == "/" || category.Url == "" {
|
||
|
idx++
|
||
|
continue
|
||
|
}
|
||
|
paths := strings.Split(strings.Trim(category.Url, "/"), "/")
|
||
|
|
||
|
var strBuilder strings.Builder
|
||
|
for i, path := range paths {
|
||
|
if len(paths) == i+1 {
|
||
|
strBuilder.WriteString(path)
|
||
|
break
|
||
|
}
|
||
|
strBuilder.WriteString(fmt.Sprintf("%s,children,", path))
|
||
|
}
|
||
|
updateNested(
|
||
|
tree,
|
||
|
strings.Split(strBuilder.String(), ","),
|
||
|
map[string]interface{}{
|
||
|
"name": category.Name,
|
||
|
"slug": category.Slug,
|
||
|
"url": category.Url,
|
||
|
"children": map[string]interface{}{},
|
||
|
},
|
||
|
)
|
||
|
tmpCategories = append(tmpCategories[:idx], tmpCategories[idx+1:]...)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func ConvertToNestedList(nestedDict map[string]interface{}) []model.TreeCategories {
|
||
|
var result []model.TreeCategories
|
||
|
|
||
|
for _, value := range nestedDict {
|
||
|
if valueMap, ok := value.(map[string]interface{}); ok {
|
||
|
childCategories := ConvertToNestedList(valueMap["children"].(map[string]interface{}))
|
||
|
|
||
|
category := model.TreeCategories{
|
||
|
Name: valueMap["name"].(string),
|
||
|
Slug: valueMap["slug"].(string),
|
||
|
Url: valueMap["url"].(string),
|
||
|
Children: childCategories,
|
||
|
}
|
||
|
|
||
|
result = append(result, category)
|
||
|
} else if category, ok := value.(model.TreeCategories); ok {
|
||
|
result = append(result, category)
|
||
|
}
|
||
|
}
|
||
|
return result
|
||
|
}
|