How to add values to map, append an array value in a map

Hi All,
I have a use case where i am creating a new map of the following type. I basically want to check if the key-value is present in the map, if so then i want to append the array of the map and insert the value. If not, then i want to initialize the array and append it.
The issue i am facing is that the map i am creating is empty- how do i add values to it, so my condition always fails. How do i fix this?
FYI: i pass a request like below to this function, which i am checking for the value in (for the map):
Request:
[{
“Category”: “TP”,
“Name”: “Golang”,
}]

type Example struct {
   Category       string `json:"category"`
   Name           string `json:"name"`
}

for i := range Example{
			dict := make(map[string][]Example)
			if count, ok := dict["Category"]; ok {
				fmt.Printf("Found %d\n", count)
			} else {
				fmt.Println("not found")
				fmt.Println(i)
			}
		}

I don’t quite understand, but does this help? https://play.golang.org/p/YqB65f3gkla

@skillian- thank you for the response. Yes something similar but how can we do it if the values need to be injected dynamically instead of declaring it as a const like in your example? The request is coming from the frontend and this is the backend endpoint.

[{
	"Category": "TP",
	"Name": "Golang"
}]

Can you show me what you mean by dynamic; can you show more examples that demonstrate that?

@skillian- i am passing the body from the frontend, this is a backend endpoint. So the request coming from the front end will be a json like below. So in my case i have to check if the Category key exists in the request, if it does i want to append that value to the array (like your example). If the key is not valid then i want to initiate an array and then append it.

Frontend request JSON:
[{
“Category”: “TP”,
"LastName":"Test",
“Name”: “Golang”,
}]

So if the request is:

[
  {
    "A": "abc",
    "B": "def"
  },
  {
    "A": "ghi",
    "C": "jkl"
  },
  {
    "A": "abc"
  }
]

The result should be:

{
  "A": [
    {
      "A": "abc",
      "B": "def"
    },
    {
      "A": "ghi",
      "C": "jkl",
    },
    {
      "A": "abc"
    }
  ],
  "B": [
    {
      "A": "abc",
      "B": "def"
    }
  ],
  "C": [
    {
      "A": "ghi",
      "C": "jkl"
    }
  ]
}

?

@skillian- Exactly. But the request will always be in this format:

[{
	"Category": "Fun",
        "LastName":"Test"
	"Name": "Golang",
	
}]


So the entry in the map array if LastName Key-Value is present in request will look like {
 {
	"Test": [
    {
      "Category": "Fun",
        "LastName":"Test"
	"Name": "Golang",
}
]
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.