0

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.

1 Answer 1

5

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"})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.