如何对哈希数组进行分组并在关键字后创建嵌套数组?

时间:2015-04-14 10:59:08

标签: ruby-on-rails ruby arrays hash

如何将哈希数组分组为一个“groupname”和“id”哈希,​​并将“words”关键字后面的元素推送到哈希数组中?我找不到类似的问题。

我的平面输入:

[{
    "id" => "1",
    "groupname" => "Unit 1",
    "words" => nil,
    "unit" => "1",
    "name" => "asdfwe"
}, {
    "id" => "1",
    "groupname" => "Unit 1",
    "words" => nil,
    "unit" => "1",
    "name" => "testasdf"
}, {
    "id" => "2",
    "groupname" => "Unit 2",
    "words" => nil,
    "unit" => "2",
    "name" => "test2wewe"
}, {
    "id" => "2",
    "groupname" => "Unit 2",
    "words" => nil,
    "unit" => "2",
    "name" => "test2sadf"
}]

期望的输出:

[{
    "id" => "1",
    "groupname" => "Unit 1",
    "words" => [{
        "unit" => "1",
        "name" => "asdfwe"
    }, {
        "unit" => "1",
        "name" => "testasdf"
    }]
}, {
    "id" => "2",
    "groupname" => "Unit 2",
    "words" => [{
        "unit" => "2",
        "name" => "test2wewe"
    }, {
        "unit" => "2",
        "name" => "test2sadf"
    }]
}]

当前未按预期步骤运作:

out = []
arrhsh.each_with_index do |hsh,index|
  hsh.each do |(k,v)|
    if k === "words"
      newhsh = {}
      newhsh["id"] = hsh["id"]
      newhsh["groupname"] = hsh["groupname"]
      newhsh["words"] = []
      wordshsh = {
        "unit" => hsh["unit"],
        "name" => hsh["name"]
      }
      newhsh["words"] << wordshsh
      out << newhshq
    end
  end
end
out.group_by {|h| h["id"]}

1 个答案:

答案 0 :(得分:1)

这个怎么样?

b = a.group_by { |i| i['id'] }.map do |id, group|
  {
    id: id,
    groupname: group.first['groupname'],
    words: group.map { |g| g.slice('unit', 'name') }
  }
end