Rails如何通过嵌套哈希进行分组

时间:2016-09-08 06:22:22

标签: ruby-on-rails arrays ruby hash

我无法解决这个问题。我在名为nested的{​​{1}}内收到了hash array。这是它的结构。

data

如您所见,第一层或第二层中有许多元素具有相同的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"
                    }
                ]
            }
        ]
    }
]

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

1 个答案:

答案 0 :(得分:2)

是的,你需要某种递归方法来递归地组合和分组嵌套的子节点。

这会产生您想要的结果:

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