【问题标题】:How to convert values of hash into array如何将哈希值转换为数组
【发布时间】:2021-11-01 11:05:10
【问题描述】:

我必须将弹性搜索结果解析为特定格式。为此,我需要将搜索结果哈希值放入数组 我有这个:

hash = {
  "ABC": {
    "attributes": {
      "id": "1",
      "from": "test",
      "to": "something",
    }
  },
  "XYZ": {
    "attributes": {
      "id": "1",
      "from": "value",
      "to": "another value",
    }
  }
}

我想解决这个问题:

"ABC": [
       {
    "attributes": {
      "id": "1",
      "from": "test",
      "to": "something",
                  }
      }],
"XYZ": [
       {
    "attributes": {
      "id": "1",
      "from": "value",
      "to": "another value",
                  }
     }
     ]

简单地说,哈希值应该是数组。请有人指导我。

【问题讨论】:

  • “and I want to get this:”后面的代码无效。我假设您想要一个哈希,在这种情况下,您需要在开头添加 { 并在末尾添加 }

标签: ruby-on-rails ruby ruby-on-rails-4


【解决方案1】:
print items.transform_values { |item| [item] }

【讨论】:

  • 虽然此代码可以回答问题,但提供有关 如何 和/或 为什么 解决问题的附加上下文将改善答案的长期价值。
【解决方案2】:

你可以试试这个。

hashmap.each { |key, value| hashmap[key] = [hashmap[key]] }

在哪里, hashmap 包含您的原始哈希。

【讨论】:

  • 有更好的方法,例如transform_values,不会改变原始哈希。
【解决方案3】:

输入

hash = {
  "ABC": {
    "attributes": {
      "id": "1",
      "from": "test",
      "to": "something",
    }
  },
  "XYZ": {
    "attributes": {
      "id": "1",
      "from": "value",
      "to": "another value",
    }
  }
}

代码

p hash.transform_values { |value| [value] }

输出

{:ABC=>[{:attributes=>{:id=>"1", :from=>"test", :to=>"something"}}], :XYZ=>[{:attributes=>{:id=>"1", :from=>"value", :to=>"another value"}}]}

【讨论】:

    猜你喜欢
    • 2015-11-26
    • 2019-10-27
    • 2019-05-23
    • 2012-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-20
    • 2015-09-13
    相关资源
    最近更新 更多