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

时间:2018-09-10 13:39:02

标签: ruby-on-rails ruby hash

在我的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"
              }
            ]
          }
        ]
      }
    ]
  }
]

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

1 个答案:

答案 0 :(得分: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"
#      }
#    }
#  }
# }