Go   发布时间:2022-04-09  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了数组 – 如何在golang中的切片中动态地将对象分配给字符串键?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图从已创建的数组创建@L_874_0@数组.我拥有的数组是

{
  "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_673_8@ 
 

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

"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_673_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@H_673_8@ 
 

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

arr             := make(map[String]interface{})
    arrCate         := make(map[String]interface{})

    for _,data := range dataVals{
      arrCate[data.Category] = data    
    }
    arr["elements"] = arrCate@H_673_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_673_8@ 
 

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

我已经花了好几个小时.任何人都可以告诉我我错过了什么?

@L_801_7@

https://play.golang.org/p/y-I6Fb_61R

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

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

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

package main

import (
    "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][]Item
type CategoryToIndexItemMap map[String]map[int]Item

func 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))

}@H_673_8@

大佬总结

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

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

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。