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.
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 does not 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"])
}