1

I have such struct defined.

type Pages struct {
  Items []map[string]string
}

In a for loop I am creating items with var item = make(map[string]string).

Complete code

pages := Pages{}
for _, partitionKey := range keys {
    fields, err := redis.Strings(conn.Do("hgetall", partitionKey))
    if err == nil {
        var item = make(map[string]string)
        item["id"] = strings.Replace(partitionKey, "pages:", "", -1)
        for i := 0; i < len(fields); i += 2 {
            key, _ := redis.String(fields[i], nil)
            value, _ := redis.String(fields[i+1], nil)
            item[key] = value
        }
        fmt.Println("\n", item)
        // this does not work
        //append(pages.Items, item)
    }
}

fmt.Println(pages)

How do I add newly created item to Items array in Pages struct?

Solution based on answers below.

type Pages struct {
    Items []map[string]string `json:"items"`
}

pages := Pages{}
for _, partitionKey := range keys {
    item, err := redis.StringMap(conn.Do("hgetall", partitionKey))
    if err == nil {
        item["id"] = strings.Replace(partitionKey, "pages:", "", -1)
        pages.Items = append(pages.Items, item)
    }
}
0

1 Answer 1

0
pages.Items = append(pages.Items, item)
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.