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

时间:2018-02-23 13:54:14

标签: go interface

作为学习的一部分,我尝试了下面的代码片段。

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
}

请帮我代码,是的,我避免使用struct,因为我正在根据上传的xlsx表准备asn对象。是的,我知道这是必需的密钥,所以我可以硬编码这个密钥来过滤。我知道它并不比javascript容易。对于编写函数我理解应该有一些返回初始化我初始化虚拟bool以避免错误。

请不要偏离问题,提出建议

理解并请逻辑帮助分组这样的[[],[]]。

这是[] map [string] interface {}

的以下示例
   [{"id":"1","seperator":"B","code":"twenty1"},
   {"id":"2","seperator":"A","code":"twenty2"},
   {"id":"3","seperator":"B","code":"twenty3"}]

seperator是分隔对象的关键内部对象。

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

1 个答案:

答案 0 :(得分:0)

听起来你想要为所识别的键对所有具有相同值的项进行分组,通常称为" group by"操作(例如,参见JavaScript,_.groupBy(...))..

实施" group by"您只需迭代给定的集合,查找目标键的值,并将当前对象追加到与键值对应的结果数组中。

例如:

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" }
  //   ]
  // }
}

请注意,以避免可能的恐慌"在上面的示例代码中,您应该使用双值类型断言形式并修改函数签名以返回两个值(映射和错误):

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
}