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"])
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?