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 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配