2
我無法解決這個問題。我在array
內部得到了nested
hash
,這叫data
。這是它的結構。Rails如何通過嵌套散列進行分組
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]}
然而,那隻組的第一層,我不知道該怎麼組嵌套結構。
這真是太神奇了,遞歸對我來說很難。感謝您的幫助! –