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 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大