gpt4 book ai didi

ruby-on-rails - Rails 如何按嵌套哈希分组

转载 作者:数据小太阳 更新时间:2023-10-29 08:43:43 25 4
gpt4 key购买 nike

我不知道如何解决这个问题。我在一个名为 dataarray 中得到了一个 nested hash。这是它的结构。

data = 
[
{
:id => 1,
:name => "S1",
:children => [
{
:id => 10,
:name => "S10",
:children => [
{
:id => 20,
:name => "S20"
}
]
}
]
},
{
:id => 1,
:name => "S1",
:children => [
{
:id => 10,
:name => "S10",
:children => [
{
:id => 21,
:name => "S21"
}
]
}
]
},
{
:id => 1,
:name => "S1",
:children => [
{
:id => 11,
:name => "S11",
:children => [
{
:id => 22,
:name => "S22"
}
]
}
]
}
]

如您所见,在第一层或第二层中有一堆具有相同 id 的元素,因此我需要对它们进行分组。

希望是这样的结果

result=  
[
{
:id => 1,
:name => "S1",
:children => [
{
:id => 10,
:name => "S10",
:children => [
{
:id => 20,
:name => "S20"
},
{
:id => 21,
:name => "S21"
}
]
},
{
:id => 11,
:name => "S11",
:children => [
{
:id => 22,
:name => "S22"
}
]
}
]
}
]

我试过类似的东西

data.group_by{|s| s[:id]}

但是,它只会对第一层进行分组,我不知道如何对嵌套结构进行分组。

最佳答案

是的,您需要某种递归方法来递归组合和分组嵌套的子项。

这会产生你想要的结果:

def group(data)
r = {}
# Combine the children
data.each do |d|
if r[d[:id]]
r[d[:id]][:children] += d[:children]
else
r[d[:id]] = d
end
end
# Now group the children
r.values.map do |d|
d[:children] = group(d[:children]) if d[:children]
d
end
end

关于ruby-on-rails - Rails 如何按嵌套哈希分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39383832/

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