将数组与整数将哈希深度指示为哈希



我有以下数组:

[{text: "a", depth: 0},
 {text: "b", depth: 1},
 {text: "c", depth: 2},
 {text: "d", depth: 1}]

我要解决的问题是要采用一个扁平的数组(上(,并根据每个元素的深度创建一个嵌套的结构。我需要它嵌套的原因是递归地构建一个列表(订购或无序(,我无法使用我的数组。

以下以某种方式,形状或形成所需的输出。我要创建的嵌套结构的一般想法应该更清楚。

  { 
    text: "a", 
    depth: 0,
    sublevel: [
      {
        text: "a",
        depth: 1,
        sublevel: [
          {
            text: "b",
            depth: 2,
            sublevel: []
          }
        ]
      },
      {
        text: "d",
        depth: 1,
        sublevel: []
      }
    ]
  }

我弄清楚了。

new_structure = []
depth = 0
array.each do |element|
  if element[:depth] == 0
    new_structure << element
  else
    if element[:depth] < depth || element[:depth] == depth
      parent = recursive_method(new_structure[-1], element[:depth] - 1)[:sublevel]
      parent = [] if parent.nil?
      parent << element
    else
      recursive_method(new_structure[-1], element[:depth]).merge!({ sublevel: [element] })
    end
  end
  depth = element[:depth]
end
def recursive_method(structure, depth)
  return structure if structure[:sublevel].nil? || depth == 0
  recursive_method(structure[:sublevel][-1], depth -= 1)
end

结果:

[
  {
    :text => "a",
    :depth => 0,
    :sublevel => [
        {
            :text => "b",
            :depth => 1,
            :sublevel => [
                {
                    :text => "c",
                    :depth => 2
                }
            ]
        }, 
        {
            :text => "d",
            :depth => 1
        }
    ]
  }
]

开放以使其变得更好。

最新更新