duansen6750 2018-09-07 13:48
浏览 8
已采纳

如何在范围内将项目追加到地图? [关闭]

Example:

package main

import (
    "encoding/json"
    "fmt"
    "github.com/imdario/mergo"
)

func main() {
    var DATA []map[string]interface{}
    text := []byte(`[{"id":1,"test":1},{"id":2},{"id":3,"test":3},{"test":8}]`)
    err := json.Unmarshal(text, &DATA)
    if err != nil {
        fmt.Errorf("ERR: %s", err)
    }

    var STATE map[string]interface{}
    var newState []interface{}

    fmt.Println("DATA: ", DATA)

    for _, k := range DATA {
        if err := mergo.Merge(&STATE, k, mergo.WithOverride); err != nil {
            fmt.Errorf("Error merge new and old packets: %s", err)
        }
        fmt.Println("STATE: ", STATE)

        newState = append(newState, STATE)
    }

    fmt.Println(newState)

}

I get: [map[id:3 test:8] map[test:8 id:3] map[id:3 test:8] map[test:8 id:3]]
I want get [map[id:1 test:1] map[test:2 id:1] map[id:3 test:3] map[test:8 id:3]]

I can not understand why the last value falls into the data slice, and not what was at the time of writing

  • 写回答

1条回答 默认 最新

  • donglu953744 2018-09-10 09:27
    关注

    I realized what the problem is, I need to explicitly copy each value

    for key,value := range STATE {
        newState[i][key] = value
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 idea自动补全键位冲突
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 定制ai直播实时换脸软件
  • ¥100 栈回溯相关,模块加载后KiExceptionDispatch无法正常回溯了
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding
  • ¥15 Marscode IDE 如何预览新建的 HTML 文件
  • ¥15 K8S部署二进制集群过程中calico一直报错
  • ¥15 java python或者任何一种编程语言复刻一个网页