2016-09-08 22 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

這真是太神奇了,遞歸對我來說很難。感謝您的幫助! –