创建嵌套哈希RUBY(Create nested hash RUBY)
我有一系列哈希,例如
array = [ { id: 1, name: 'root' parent: null}, { id: 2, name: 'first' parent: 1}, { id: 5, name: 'first step' parent: 2}, { id: 6, name: 'second step' parent: 2}, { id: 3, name: 'second' parent: 1}, { id: 7, name: 'first step' parent: 3}, { id: 4, name: 'third' parent: 1}, { id: 2, name: 'first' parent: 1},]
我需要建立类似的东西
hash = { { id: 1, name: 'root', parent: null, childrens: [ { id: 2, name: 'first', parent: 1, childrens: [ { id: 5, name: 'first step', parent: 2 }, { id: 6, name: 'second step', parent: 2 }, ]}, ... }我是ruby的新手,并不知道如何做到这一点。 可能我需要使用递归函数? 或不?
i have an array of hashes, eg
array = [ { id: 1, name: 'root' parent: null}, { id: 2, name: 'first' parent: 1}, { id: 5, name: 'first step' parent: 2}, { id: 6, name: 'second step' parent: 2}, { id: 3, name: 'second' parent: 1}, { id: 7, name: 'first step' parent: 3}, { id: 4, name: 'third' parent: 1}, { id: 2, name: 'first' parent: 1},]
and i need to build something like that
hash = { { id: 1, name: 'root', parent: null, childrens: [ { id: 2, name: 'first', parent: 1, childrens: [ { id: 5, name: 'first step', parent: 2 }, { id: 6, name: 'second step', parent: 2 }, ]}, ... }I am newbie at ruby and doesnot understand how to do this. Probably i need to use recursive functions? Or not?
最满意答案
# Put all your nodes into a Hash keyed by id This assumes your objects are already Hashes object_hash = nodes.index_by {|node| node[:id]} object_hash[0] = {:root => true} # loop through each node, assigning them to their parents object_hash.each_value {|node| next if node[:root] children = object_hash[node[:parent_id]][:children] ||= [] children << node } #then your should have the structure you want and you can ignore 'object_hash' variable tree = object_hash[0]从答案:
用于将平面树解析为非平面树的算法
# Put all your nodes into a Hash keyed by id This assumes your objects are already Hashes object_hash = nodes.index_by {|node| node[:id]} object_hash[0] = {:root => true} # loop through each node, assigning them to their parents object_hash.each_value {|node| next if node[:root] children = object_hash[node[:parent_id]][:children] ||= [] children << node } #then your should have the structure you want and you can ignore 'object_hash' variable tree = object_hash[0]From the answer:
Algorithm for parsing a flat tree into a non-flat tree
更多推荐
发布评论