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]}
然而,那只组的第一层,我不知道该怎么组嵌套结构。
这真是太神奇了,递归对我来说很难。感谢您的帮助! –