如何将哈希数组分组为一个“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"]}
答案 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