数组 – 如何在golang中的切片中动态地将对象分配给字符串键?

数组 – 如何在golang中的切片中动态地将对象分配给字符串键?,第1张

概述我试图从已创建的数组创建一个数组.我拥有的数组是 { "id": 1, "category": "fruits", "name": "Apple", "description": "Apple is my favorite fruit."}{ "id": 2, "category": "colors", "name": "Red", "description" 我试图从已创建的数组创建一个数组.我拥有的数组是

@H_419_8@

@H_419_8@

{  "ID": 1,"category": "fruits","name": "Apple","description": "Apple is my favorite fruit."}{  "ID": 2,"category": "colors","name": "Red","description": "Red color is always charming."}{  "ID": 3,"category": "flowers","name": "Lotus","description": "It is one of the most beautiful flowers in this world."}{  "ID": 4,"name": "Pink","description": "A romantic color,mostly liked by women."}{  "ID": 5,"name": "Rose","description": "I love roses."}{  "ID": 6,"name": "Mango","description": "Mango is one of my favorite fruits."}

现在我需要创建一个数组并填充数据,如:@H_419_8@

@H_419_8@

"elements":{   "fruits":{      0:{         "ID": 1,"description": "Apple is my favorite fruit."       }     1:{        "ID": 6,"description": "Mango is one of my favorite fruits."       }     }    "flowers":{        0:{            "ID": 3,"description": "It is one of the most beautiful flowers in this world."         }        1:{          "ID": 5,"description": "I love roses."        }      }    "colors":{       0:{          "ID": 2,"description": "Red color is always charming."        }      1:{        "ID": 4,mostly liked by women."       }     }}

我试过的是:@H_419_8@

@H_419_8@

arr             := make(map[string]interface{})    arrCate         := make(map[string]interface{})    arrCateFlower   := make(map[int]interface{})    arrCatecolor    := make(map[int]interface{})    arrCateFruit    := make(map[int]interface{})    for index,data := range dataVals{        if(data.category == "flower"){            arrCateFlower[index] = data        }        if(data.category == "colors"){            arrCatecolor[index] = data          }        if(data.category == "fruits"){            arrCateFruit[index] = data          }    }    arrCate["flowers"] = arrCateFlower    arrCate["colors"] = arrCatecolor    arrCate["fruits"] = arrCateFruit    arr["elements"] = arrCate

其中dataVals包含顶部给出的未格式化数据.通过应用上面的代码,我能够得到正确的输出.但我不认为这是有效的方式.如果我尝试类似的东西@H_419_8@

@H_419_8@

arr             := make(map[string]interface{})    arrCate         := make(map[string]interface{})    for _,data := range dataVals{      arrCate[data.category] = data        }    arr["elements"] = arrCate

然后我得到类似的东西:@H_419_8@

@H_419_8@

"elements":{   "fruits":{              "ID": 6,"description": "Mango is one of my favorite fruits."            }    "flowers":{               "ID": 5,"description": "I love roses."              }    "colors":{               "ID": 4,mostly liked by women."              }}

循环中该特定类别的最后一个元素.我不明白如何在不使用代码中的任何静态值的情况下获取数组中的所有元素.@H_419_8@

我已经花了好几个小时.任何人都可以告诉我我错过了什么?@H_419_8@解决方法 https://play.golang.org/p/y-I6Fb_61R

@H_419_8@

我希望你可以使用额外的外部{}对.@H_419_8@

没有外{}对:https://play.golang.org/p/SSTgln0qJc@H_419_8@

为了不仅仅有一堆链接并且让其他人容易批评我的解决方案,我在这里包含了代码,稍作修改:@H_419_8@

@H_419_8@

package mainimport (    "fmt"    "enCoding/Json"    "log"    "strings")var dataAsstring = `` //put data between the ``type Item struct {    ID          int    `Json:"ID"`    category    string `Json:"category"`    name        string `Json:"name"`    Description string `Json:"description"`}type categoryToItemSliceMap map[string][]Itemtype categoryToIndexItemmap map[string]map[int]Itemfunc main() {    // first read the data,we use a decoder as the input was given    // as a stream of seperate Json objects and not a big single one.    decoder := Json.NewDecoder(strings.NewReader(dataAsstring))    var ourData []Item    for decoder.More() {        var it Item        err := decoder.Decode(&it)        if err != nil {            log.Fatalln(err)        }        ourData = append(ourData,it)    }    // collect items according to categorIEs    catToItemSlice := categoryToItemSliceMap{}    for _,v := range ourData {        catToItemSlice[v.category] = append(catToItemSlice[v.category],v)    }    // turn those slices into int -> Item maps so we get the index numbers    // in the encoded Json    catToIndexItemmap := categoryToIndexItemmap{}    for k,v := range catToItemSlice {        if catToIndexItemmap[k] == nil {            catToIndexItemmap[k] = map[int]Item{}        }        for index,item := range v {           catToIndexItemmap[k][index] = item        }    }    // easIEst way to get the "elements: " without an additional outer {}     // brace pair    fmt.Printf("elements: ")    // We only have one Json object in the output and that is a map,so we    // can use Unmarshal and don't need a streaming encoder. And get nice    // indentation with Marshalindent.    out,err := Json.Marshalindent(catToIndexItemmap,"","    ")    if err != nil {        log.Fatalln(err)    }    fmt.Println(string(out))}
总结

以上是内存溢出为你收集整理的数组 – 如何在golang中的切片中动态地将对象分配给字符串键?全部内容,希望文章能够帮你解决数组 – 如何在golang中的切片中动态地将对象分配给字符串键?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1265605.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-08
下一篇 2022-06-08

发表评论

登录后才能评论

评论列表(0条)

保存