在Ruby中将哈希数组转换为嵌套哈希数组

问题描述 投票:-3回答:1

在我的ruby on rails应用程序中,我从API服务获取数据,数据格式是下面的哈希数组。

data = [
  {"category": "Population.Behaviors.Commute", "tag": "away", "description": "Work Outside the Home"},
  {"category": "Population.Behaviors.Commute.Vehicle", "tag": "mbike", "description": "Bike to Work"}
]

上面的代码格式我必须转换为以下格式来生成表单元素。

response_format = [
  {
    "label": "Population",
    "options": [
      {
        "label": "Behaviors",
        "options": [
          {
            "label": "Commute",
            "options": [
              {
                "label": "Vehicle",
                "options": [
                  {
                    "tag": "mbike",
                    "description": "Bike to Work"
                  }
                ]
              },
              {
                "tag": "away",
                "description": "Work Outside the Home"
              }
            ]
          }
        ]
      }
    ]
  }
]

任何人都可以帮助实现解决方案。

ruby-on-rails ruby hash
1个回答
2
投票

您只需要递归地构建内部哈希:

data.
  each_with_object(Hash.new { |h, k| h[k] = h.dup.clear }) do |h, acc|
   (h[:category].split('.').
        reduce(acc) do |inner, cat|
          inner["label"] = cat
          inner["options"] ||= {}
        end || {}).
     merge!("tag" => h[:tag], "description" => h[:description])
  end
#⇒ {
#    "label" => "Population",
#  "options" => {
#      "label" => "Behaviors",
#    "options" => {
#        "label" => "Commute",
#      "options" => {
#        "description" => "Work Outside the Home",
#              "label" => "Vehicle",
#            "options" => {
#          "description" => "Bike to Work",
#                  "tag" => "mbike"
#        },
#                "tag" => "away"
#      }
#    }
#  }
# }
© www.soinside.com 2019 - 2024. All rights reserved.