使用深度嵌套的地图以递归方式填充结构列表

时间:2019-06-26 20:31:50

标签: go recursion

我有一个map[string]map[string]map[string]interface{}类型的映射,我想创建以下类型的结构:

type Item struct {
    Name string,
    Id string,
    Items []Item
}

由于地图的深度会随着时间变化,因此我试图使用递归来创建Item列表。

items := make([]Items, 0, 5)
for key, value := range resp {
     //Where resp is the map of the type map[string]map[string]map[string]interace{}
     tempMap := make(map[string]interface{})
     tempMap[key] = value
     items = buildItems(tempMap, names) //Names would be the function which would take the Id and set the name
}

func buildItems(items map[string]interface{}, names ) []Items {
    result := make([]Items, 0, 10)
    for parent, children := range items {
        item := names(parent, names)
        if children != nil {
            //The Problem
            item.Items = buildItems(children, names)
        }
    }
    return result
}

问题 1.为了让我调用buildItems,我需要将项目设置为map [string] interface {},为此,我需要知道需要另一个for循环的下一个键 2.我不确定返回父母的正确方法是什么,等等

示例响应可能类似于

0566146
     605679
         6056
             <nil> 
     60566
         606
             <nil>
     6056614
         606584
             <nil>
60653
     606536
         6109
             <nil>
         60784
             <nil>
         61099
             <nil>
     6065
         6112
             <nil>
         61129
            <nil>
         6078
             <nil>
         6084
             <nil>
         61097
             <nil>
         6108
            <nil>
         6110
             <nil>
         61099
             <nil>
60675
     606756
         60722
             <nil>
         6096
             <nil>
         609705
             <nil>
         60773
             <nil>

0 个答案:

没有答案
相关问题