在ruby中将hash-inside-array转换为单键多值哈希

时间:2018-05-03 07:38:10

标签: ruby-on-rails ruby

我正在尝试从redis db加载数据。我有一个api only rails app并尝试按照要求呈现json数据。 目前,我能够以下列格式get来自redis的数据。

[
 {
  "id": 1,
  "name": "Stephenie Meyer",
  "created_at": "2018-04-17T07:40:50.417Z",
  "updated_at": "2018-04-17T07:40:50.417Z"
 },
 {
  "id": 2,
  "name": "V.C. Andrews",
  "created_at": "2018-04-17T07:40:50.613Z",
  "updated_at": "2018-04-17T07:40:50.613Z"
 },
 {
  "id": 3,
  "name": "Sophie Kinsella",
  "created_at": "2018-04-17T07:40:50.646Z",
  "updated_at": "2018-04-17T07:40:50.646Z"
 }
]

如何以namecreatedupdated的键值对散列到id键值对的方式进行转换。< / p>

进入这个

 {"id": 1,
    {
      "name": "Stephenie Meyer",
      "created_at": "2018-04-17T07:40:50.417Z",
      "updated_at": "2018-04-17T07:40:50.417Z"
    }
 }

获取redis数据的辅助方法。

def fetch_authors
    authors = $redis.get('authors')
    if authors.nil?
      authors = Author.all.to_json
      $redis.set("authors", authors).to_json
      $redis.expire("authors", 5.hour.to_i)
    end
    JSON.load authors
end

使用

在索引页面上显示
def index
    @authors = fetch_authors
    render json: @authors
  end

2 个答案:

答案 0 :(得分:1)

最接近你想要的可能是:

input = ...
input.map { |hash| [hash.delete(:id) || hash.delete('id'), hash] }.to_h

#⇒ {{1=>{:name=>...},
#   {2=>{:name=>...},
#   {3=>{:name=>...}}

答案 1 :(得分:0)

不完全是您想要的,因为语法不正确,但您可以使用group_by

来实现类似的功能
arr = [
  {
    "id": 1,
    "name": "Stephenie Meyer",
    "created_at": "2018-04-17T07:40:50.417Z",
    "updated_at": "2018-04-17T07:40:50.417Z"
  },
  {
    "id": 2,
    "name": "V.C. Andrews",
    "created_at": "2018-04-17T07:40:50.613Z",
    "updated_at": "2018-04-17T07:40:50.613Z"
  },
  {
    "id": 3,
    "name": "Sophie Kinsella",
    "created_at": "2018-04-17T07:40:50.646Z",
    "updated_at": "2018-04-17T07:40:50.646Z"
  }
]

arr.group_by { |e| e[:id] }

这将返回

{
    1 => [
        {
                    :id => 1,
                  :name => "Stephenie Meyer",
            :created_at => "2018-04-17T07:40:50.417Z",
            :updated_at => "2018-04-17T07:40:50.417Z"
        }
    ],
    2 => [
        {
                    :id => 2,
                  :name => "V.C. Andrews",
            :created_at => "2018-04-17T07:40:50.613Z",
            :updated_at => "2018-04-17T07:40:50.613Z"
        }
    ],
    3 => [
        {
                    :id => 3,
                  :name => "Sophie Kinsella",
            :created_at => "2018-04-17T07:40:50.646Z",
            :updated_at => "2018-04-17T07:40:50.646Z"
        }
    ]
}