首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >转换深嵌套的ruby散列

转换深嵌套的ruby散列
EN

Stack Overflow用户
提问于 2016-06-28 19:58:34
回答 1查看 86关注 0票数 0

我有一个深嵌套的Ruby哈希,需要将其转换为另一个哈希。哈希可能有0或更多的子。,这是输入散列:

代码语言:javascript
复制
"{'id' => 'apple', 'children' => [{'id' => 'ipad', 'children' => [{'id' => 'ipadmini'}]},{'id' => 'ipadmini'}]}"

输出

代码语言:javascript
复制
[{"ipad"=>{"id"=>"ipad", "paths"=>[[{"id"=>"apple"}, {"id"=>"ipad"}]]}},
{"ipadmini"=>{"id"=>"ipadmini", "paths"=>[[{"id"=>"ipad"}, {"id"=>"ipadmini"}], [{"id"=>"apple"}, {"id"=>"ipad"}, {"id"=>"ipadmini"}]]}}, {"apple"=>{"id"=>"apple", "paths"=>[[{"id"=>"apple"}]]}}]

我的代码:

代码语言:javascript
复制
def construct_concept(concept)
    h = {}
    c = Hash[*concept.to_a.first]
    c['paths'] = [[Hash[*concept.to_a.first]]]
    h[concept['id']] = c
    h
end

def parent_child_concepts(concepts)
    pc = {}
    pc[:parent] = Hash[*concepts.first]
    pc[:children] = concepts.values_at('children').flatten.map {|child| parent_child_concepts(child)} || []
    pc
end

def add_parent_child_paths(parent_hash,children_array)
    h = {}
    parent_hash.each do |parent_key,parent_value|
        h[parent_key] = parent_value
        children_array.each do |child|
            child.each do |k,v|
                h[k] = v
                h[k]['paths'].map {|path| path.unshift({'id' => parent_key})}
            end
        end
    end
    h
end

def build_concept_data(concepts)
    #concept {"id"=>"apple", "children"=>[{"id"=>"ipad"}]}
    parsed_concepts = parent_child_concepts(concepts)
    parent = construct_concept(parsed_concepts[:parent])
    children = parsed_concepts[:children].each_with_object([]) {|child,accu| accu << construct_concept(child)}
    concept_paths_data = add_parent_child_paths(parent,children)
end
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-06-30 21:29:42

代码语言:javascript
复制
def build_data(node, ctx = [], result = [])
  id = node['id']
  children = node['children']

  branch = result.find{|h| h.has_key?(id)}
  if branch.nil?
    result.push({
      id => {
        'id' => id,
        'paths' => []
      }
    })
  end
  branch = result.find{|h| h.has_key?(id)}
  branch[id]['paths'].unshift(
    [ctx, id].flatten.map do |ctx_id|
      {
        'id' => ctx_id
      }
    end
  )

  if children.is_a?(Array)
    children.each do |node|
      new_ctx = ctx.dup
      new_ctx.push(id)
      nesting(node, new_ctx, result)
    end
  end

  result
end
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38085242

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档