How to build a structure tree from a slice of struct?

Issue

here are my initial model

type Team struct {
    Id    string `json:"id"`
    Name  string `json:"name"`
    Level int64  `json:"level"`
}

type TeamTree struct {
    Teams []Team     `json:"teams"`
    Child []TeamTree `json:"child"`
}

Sample data:

 id     team      level
 a      BOD         1
 b      Marketing   2
 c      Dev         2
 d      Worker      3

I want to have this result (should be a mapping):

{
    "teams": [
        {"id": "a", "team": "BOD", "level": 1}
    ],
    "child": {
        "teams": [
            {"id":"b", "team": "marketing", "level": 2},
            {"id":"c", "team": "marketing", "level": 2}
        ],
        "child": {
            "teams": [
                {"id": "d", "team": "worker", "level": 3}
            ],
            "child"": {}
        }

    }
}

I was told to do self loop, but I do not know how to do it, since I keep getting error and my code cant even run.

Solution

This is a full example of what you want

package main

import "log"

type Team struct {
    id    string
    name  string
    level int64
}

type TeamTree struct {
    teams    []Team
    children []TeamTree
}

func main() {
    firstChild := TeamTree{teams: []Team{{id: "firstChildId", name: "First", level: 10}}, children: make([]TeamTree, 0)}
    secondChild := TeamTree{teams: []Team{{id: "secondChildId", name: "Second", level: 20}}, children: make([]TeamTree, 0)}
    thirdChild := TeamTree{teams: []Team{{id: "thirdChildId", name: "Third", level: 30}}, children: make([]TeamTree, 0)}
    rootTeamTree := TeamTree{teams: []Team{{id: "rootId", name: "Root", level: 100}}, children: []TeamTree{firstChild, secondChild, thirdChild}}

    log.Println("What's the second child's level:", rootTeamTree.children[1].teams[0].level)
}

And this is the result

2022/06/19 08:24:55 What's the second child's level: 20

Answered By – Hamed Rajabi

Answer Checked By – Senaida (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.