-1

私はこの配列の配列を持っています:

[["abc", "123"], ["cde", "456"], ["cde", "674"]]

そして、この配列の配列を次のように配置します。

{ "name": "test", "children": [ {"name": "abc", "children": [ {"name": "123"} ]}, {"name": "cde", "children": [ { "name": "456"},{"name": "674"} ]}]}

Ruby言語でこの変換を行うにはどうすればよいですか?

前もって感謝します。

4

1 に答える 1

2

これを試して

 require 'json'
 src_arr= [["abc", "123"], ["cde", "456"], ["cde", "674"]]
 tmp = {} # to collect all common node first
 src_arr.each do |arr|
     if node = tmp[arr.first] # check if node exists
       node['children'] << {'name' => arr.last} # append of exists
     else
       # add node if does not exists
       tmp[arr.first] = {'name' => arr.first,'children' => [{'name' => arr.last}]}
     end
   end
 tree = {'name' => 'test','children' => tmp.values}
 puts tree

#=> {"name"=>"test", "children"=>[{"name"=>"abc", "children"=>[{"name"=>"123"}]}, {"name"=>"cde", "children"=>[{"name"=>"456"}, {"name"=>"674"}]}]}

puts JSON.generate(tree)

#=> {"name":"test","children":[{"name":"abc","children":[{"name":"123"}]},{"name":"cde","children":[{"name":"456"},{"name":"674"}]}]}
于 2013-07-30T15:43:46.770 に答える