How to group array of hashes into one "groupname" and "id" hash and push elements occurring after "words" keyword into array of hashes? I can't find similar issue.
My flat input:
[{
"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"
}]
Desired output:
[{
"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"
}]
}]
Current not working as expected steps:
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"]}