2016-09-08 17 views
2

我无法解决这个问题。我在array内部得到了nestedhash,这叫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]} 

然而,那只组的第一层,我不知道该怎么组嵌套结构。

回答

1

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

这将产生你想要的结果:

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 
+0

这真是太神奇了,递归对我来说很难。感谢您的帮助! –