ruby-on-rails - 如何对散列数组进行分组并在关键字后创建嵌套数组?

标签 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"]}

最佳答案

这个呢?

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

关于ruby-on-rails - 如何对散列数组进行分组并在关键字后创建嵌套数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29625637/

相关文章:

ruby-on-rails - 用于多态的 _type 列是什么?

javascript - 在 rails 中测试 js.erb 文件

c++ - 从 C++ 程序调用 Rails 方法

ruby-on-rails - 如何在 ruby​​ on rails 中获得 elasticsearch 性能优化

ruby - 有人可以提供 Thor::HiddenTask 用法的示例吗?

java - 如何克服 ArrayList 字符串分隔 ""和 ' ' ?

ruby-on-rails - 在一个方法中传递时,使变量在 Controller 的所有方法中可用

ruby-on-rails - 对象.有效?返回 false 但 object.errors.full_messages 为空

c++ - 是否可以使用 begin() 和 end() 创建 std::array?

javascript - 如何释放 JavaScript 中的内存