ruby - 将哈希树转换为具有深度键的哈希数组

标签 ruby arrays hashmap

给定一个像这样的哈希树:

hash_tree = {
  <Category id: 1, title: "foo"> => {},
  <Category id: 2, title: "bar"> => {
    <Category id: 3 title: "baz"> => {
      <Category id: 4 title: "qux"> => {}
    }
  },
  <Category id: 5, title: "norf"> => {}
}

我想要一种优雅的方式来创建散列的平面数组,并保留顺序,并将深度添加到每个散列作为键,例如:

flat_array = [
  { value: 1, text: "foo", depth: 0 },
  { value: 2, text: "bar", depth: 0 },
  { value: 3, text: "baz", depth: 1 },
  { value: 4, text: "quz", depth: 2 },
  { value: 5, text: "norf", depth: 0 }
]

组成哈希树的每个对象都比上面的示例复杂得多,具有更多属性,但我的数组中需要的只是 ID 和标题 - 但请注意,键已更改。

谢谢

最佳答案

我将您的 hash_tree 更改为开放结构,以便我可以使用它,但我想我得到了您想要的:

require 'ostruct'

hash_tree = {
  OpenStruct.new(id: 1, title: "foo") => {},
  OpenStruct.new(id: 2, title: "bar") => {
    OpenStruct.new(id: 3, title: "baz") => {
      OpenStruct.new(id: 4, title: "qux") => {}
    }
  },
  OpenStruct.new(id: 5, title: "norf") => {}
}


def flat_tree(hash, depth = 0)
  hash.each_with_object([]) do |(obj, v), results|
    results << { value: obj.id, text: obj.title, depth: depth }
    results << flat_tree(v, depth + 1) if v.is_a?(Hash) && !v.empty?
  end
end

puts flat_tree(hash_tree)

输出:

{:value=>1, :text=>"foo", :depth=>0}
{:value=>2, :text=>"bar", :depth=>0}
{:value=>3, :text=>"baz", :depth=>1}
{:value=>4, :text=>"qux", :depth=>2}
{:value=>5, :text=>"norf", :depth=>0}

关于ruby - 将哈希树转换为具有深度键的哈希数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29844412/

相关文章:

ruby-on-rails - 在 irb 中阅读文档

sql - 了解为什么我的 Rails 4 应用程序随机超时

arrays - 如何使用 ndarray 从向量的向量创建二维数组?

arrays - 动态创建数组的关联数组

c++ - hash_map 不工作

ruby - 代理后面的 net/imap

ruby - 它对 .ruby-version 视而不见

c++ - 将 char[][] 转换为 char**

java - 如何从Java 7中的.txt文件提取主机名和主机请求的出现?

hashmap - 如何解决 Rust 对 HashMap 的借用检查?