Home > Mobile >  How to make array of objects that contains key-values in golang?
How to make array of objects that contains key-values in golang?

Time:07-21

Let's say, I am iterating some data in go for loop.

for _, job := range orderJobs {}

for each iteration, I want a new object to be added in array and that object should contain the key value pairs.

So the final output should be something like

[
{
"order_id":"123"
"job_name":"JOB1"
}
{
"order_id":"456"
"job_name":"JOB2"
}
]

Should I declare and use go maps in this case ? If yes then how exactly I should declare ?

I tried declaring

Jobs := make(map[string]interface{})

and inserting key value pairs like below inside loop iteration

Jobs["order_id"] = "123"

it's not serving the purpose of creating array of objects.

CodePudding user response:

Declare jobs as a slice:

 var jobs []map[string]any

Append values to the slice in the for loop:

 jobs = append(jobs, map[string]any{"order_id": "123", "job_name":"JOB1"})
  •  Tags:  
  • go
  • Related