英文:
How can I create an object of objects in Golang with data taken from an array?
问题
如果我有这个数组:
type Person struct {
ID string `json:"id"`
Name string `json:"name"`
Address string `json:"address"`
}
var Group = []Person{
{
ID: "1",
Name: "Linda",
Address: "London",
},
{
ID: "2",
Name: "George",
Address: "Paris",
},
{
ID: "3",
Name: "John",
Address: "Amsterdam",
},
}
我该如何生成一个对象,其中每个特定值都是键,其余的键值对在其中,如下所示:
var Object = {
Linda: {
ID: "1",
Address: "London",
},
George: {
ID: "2",
Address: "Paris",
},
John: {
ID: "3",
Address: "Amsterdam",
},
}
这可能不是最聪明的问题,但请帮忙!
英文:
If I have this array:
type Person struct {
ID string `json:"id"`
Name string `json:"name"`
Address string `json:"address"`
}
var Group = []Person{
{
ID: "1",
Name: "Linda",
Address: "London",
},
{
ID: "2",
Name: "George",
Address: "Paris",
},
{
ID: "3",
Name: "John",
Address: "Amsterdam",
},
}
How can I generate an object of objects in each of which a particular value is the key and the rest of the key-value pairs are in, as in:
var Object = {
Linda: {
ID: "1",
Address: "London",
},
George: {
ID: "2",
Address: "Paris",
},
John: {
ID: "3",
Address: "Amsterdam",
},
}
Not the smartest question in town I know, but please help!
答案1
得分: 3
我不完全确定你在这里所指的"Object"是什么意思,但是实现这个的一种方法是使用map
。
例如:
package main
import "fmt"
func main(){
type Person struct {
ID string `json:"id"`
Name string `json:"name"`
Address string `json:"address"`
}
var Group = []Person{
{
ID: "1",
Name: "Linda",
Address: "London",
},
{
ID: "2",
Name: "George",
Address: "Paris",
},
{
ID: "3",
Name: "John",
Address: "Amsterdam",
},
}
personMap := map[string]Person{}
for _, person := range Group {
personMap[person.Name] = person
}
fmt.Println(personMap)
// 输出: map[George:{2 George Paris} John:{3 John Amsterdam} Linda:{1 Linda London}]
}
然后,你可以通过personMap["Linda"]
来访问Person
对象。
英文:
I'm not entirely sure what you mean by Object here but one way to accomplish this would be via a map
.
For example:
package main
import "fmt"
func main(){
type Person struct {
ID string `json:"id"`
Name string `json:"name"`
Address string `json:"address"`
}
var Group = []Person{
{
ID: "1",
Name: "Linda",
Address: "London",
},
{
ID: "2",
Name: "George",
Address: "Paris",
},
{
ID: "3",
Name: "John",
Address: "Amsterdam",
},
}
personMap := map[string]Person{}
for _, person := range Group {
personMap[person.Name] = person
}
fmt.Println(personMap)
// Outputs: map[George:{2 George Paris} John:{3 John Amsterdam} Linda:{1 Linda London}]
}
You could then access an a Person
from the map via personMap["Linda"]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论