创建嵌套哈希RUBY(Create nested hash RUBY)

编程入门 行业动态 更新时间:2024-10-26 08:20:50
创建嵌套哈希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

更多推荐

本文发布于:2023-07-22 01:02:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1215514.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   RUBY   Create   nested   hash

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!