我有一系列哈希,例如
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的新手,并不了解如何做到这一点。 可能我需要使用递归函数?或者不是?
答案 0 :(得分:1)
# 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]
答案: