duanfu1873 2019-03-08 18:39
浏览 57
已采纳

如何检查值是否存在于struct中并在数组中保存另一个值

I'm not exactly sure how to do this in Go, I'm just starting to work with it so I'm not familiar on how it should be done.

The idea is this: I have a struct created inside a function:

XSiteGroup := struct {
        siteURL string
        siteIDs []string
    }{}

I have implemented a request that gets an array of objects; this objects have the following structure:

{
   "siteId": "",
   "merchantName": "",
   "friendlyTitle": "",
   "url": ""
 }

What I'm trying to do is loop through that array and store each url I find as a "key" without duplicates, and then store the siteId value of each object on the siteIDs array of the struct XSiteGroup. So let's say the following scenario:

{
   "siteId": "5050",
   "merchantName": "",
   "friendlyTitle": "",
   "url": "url1.com"
},
{
   "siteId": "4050",
   "merchantName": "",
   "friendlyTitle": "",
   "url": "url2.com"
},
{
   "siteId": "8060",
   "merchantName": "",
   "friendlyTitle": "",
   "url": "url1.com"
}

Having the result from above, I would need to store something like:

{
  siteURL: "url1.com",
  siteIDs: ["5050", "8060"]
}

I have something like this at the moment to loop the array of sites I have:

for _, site := range xwebsites {
        u, _ := url.Parse(site.URL)
        urlString := strings.ReplaceAll(u.Host, "www.", "")

        // So I'm thinking here I should handle the struct I created to store values 
        }

Please let me know if I'm not clear or what additional information is needed.

  • 写回答

1条回答 默认 最新

  • douxianglu4370 2019-03-08 19:29
    关注

    If the value doesn't exist, you have to create it. You can check that with value, ok := map[key].

    type xsitegroup struct {
        url     string
        ids     []string
    }
    
    # A mapping between urls and their site groups.
    sitegroups := make(map[string]*xsitegroup)
    
    for _, website := range xwebsites {
        url := website["url"]
    
        sitegroup, ok := sitegroups[url]
    
        # A sitegroup for this URL doesn't exist
        if !ok {
            # Create the sitegroup
            sitegroup = &xsitegroup{ url: url, ids: []string{} }
            # Add it to the mapping
            sitegroups[url] = sitegroup
        }
    
        # Append the site id.   
        sitegroup.ids = append(sitegroup.ids, website["siteId"])
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python