douzhiji2020 2018-02-23 13:54
浏览 416
已采纳

基于map接口数组中键的golang过滤器

As part of learning, i was tried the below code snippets.

func ASNGroup(asn []map[string]interface{}) bool {
    eachgroup := make([][]map[string]interface{}, 0)

    for i := range asn {
        for _, v := range asn[i] {
            // How to filter the based on Key based on the below filter i should group the above asn array maps.
                    asn[i]["ID"]    
        }
    }
    fmt.Println(eachgroup)

    return true
}

Please help me in code and Yes i avoided struct because i m preparing the asn object based on the xlsx sheet uploaded. Yes, i know this is the mandatory key so that i can hard code this key to filter. I understand it is not as easy than javascript. for writing functions i understand there should be some return initialization i initialized dummy bool for to avoid errors.

please don't deviate the issue, with suggestions

Understand and please help in logic to group something like this [[],[]].

this is the below example of []map[string]interface{}

   [{"id":"1","seperator":"B","code":"twenty1"},
   {"id":"2","seperator":"A","code":"twenty2"},
   {"id":"3","seperator":"B","code":"twenty3"}]

seperator is the key inside object to seperate the objects.

{"B" : [{"id":"1","seperator":"B","code":"twenty1"},
{"id":"3","seperator":"B","code":"twenty3"}]
, "A" :  [{"id":"2","seperator":"A","code":"twenty2"}]}
  • 写回答

1条回答 默认 最新

  • doutun1875 2018-02-23 14:16
    关注

    It sounds like you want to group all items with the same value for the identified key, often called a "group by" operation (see, for example, in JavaScript, _.groupBy(...))..

    To implement "group by" you simply need to iterate over the given collection, lookup the value for the target key, and append the current object to the result array corresponding to the value of the key.

    For example:

    func groupBy(maps []map[string]interface{}, key string) map[string][]map[string]interface{} {
      groups := make(map[string][]map[string]interface{})
      for _, m := range maps {
        k := m[key].(string) // XXX: will panic if m[key] is not a string.
        groups[k] = append(groups[k], m)
      }
      return groups
    }
    
    func main() {
      xs := []map[string]interface{}{
        {"id": "1", "seperator": "B", "code": "twenty1"},
        {"id": "2", "seperator": "A", "code": "twenty2"},
        {"id": "3", "seperator": "B", "code": "twenty3"},
      }
      grouped := groupBy(xs, "seperator")
      // {
      //   "A": [
      //     { "code": "twenty2", "id": "2", "seperator": "A" }
      //   ],
      //   "B": [
      //     { "code": "twenty1", "id": "1", "seperator": "B" },
      //     { "code": "twenty3", "id": "3", "seperator": "B" }
      //   ]
      // }
    }
    

    Note that to avoid the possible "panic" in the sample code above you should use the two-value type assertion form and modify your function signature to return two values (map and error):

    func groupBy(...) (map..., error) {
      //...
        k, ok := m[key].(string)
        if !ok {
          return nil, fmt.Errorf("expected string value type for key %q, got %T", key, m[key])
        }
      // ...
      return groups, nil
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程