我有这个数组数组:
[["abc", "123"], ["cde", "456"], ["cde", "674"]]
我希望以这种方式排列这个数组:
{ "name": "test", "children": [ {"name": "abc", "children": [ {"name": "123"} ]}, {"name": "cde", "children": [ { "name": "456"},{"name": "674"} ]}]}
如何用ruby语言进行转换?
提前致谢。
答案 0 :(得分: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"}]}]}