-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 回答