Home > database >  How can I create an object of objects in Golang with data taken from an array?
How can I create an object of objects in Golang with data taken from an array?

Time:10-14

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!

CodePudding user response:

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"]

  •  Tags:  
  • go
  • Related