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)
}
}
@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.
@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.
@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",
}
]
}