"1", -6ren">
gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:23:35 25 4
gpt4 key购买 nike

如何将散列数组分组为一个“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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com