如何在Golang中创建包含键值对的对象数组?

huangapple go评论75阅读模式
英文:

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

问题

假设我正在使用Go语言的for循环迭代一些数据。

for _, job := range orderJobs {}

在每次迭代中,我希望在数组中添加一个新的对象,该对象应包含键值对。

所以最终的输出应该类似于:

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

在这种情况下,我应该声明并使用Go的映射吗?如果是的话,我应该如何声明?

我尝试声明:

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

并在循环迭代中像下面这样插入键值对:

Jobs["order_id"] = "123"

但它没有达到创建对象数组的目的。

英文:

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

得分: 4

声明一个切片变量jobs:

 var jobs []map[string]any

在for循环中向切片中添加值:

 jobs = append(jobs, map[string]any{"order_id": "123", "job_name":"JOB1"})
英文:

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"})

huangapple
  • 本文由 发表于 2022年7月20日 22:13:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/73053262.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定