如何获取数组的一部分并形成一个新数组?

时间:2018-08-25 17:54:16

标签: ruby-on-rails

我正在构建Rails 5应用程序。 在此应用程序中,我已连接到Google Calendar API。 连接工作正常,我得到了日历列表。 我需要做的是获取从Google获得的该JSON对象的ID和摘要。

这就是我得到的

    [{
        "kind": "calendar#calendarListEntry",
        "etag": "\"1483552200690000\"",
        "id": "xxx.com_asae@group.calendar.google.com",
        "summary": "My office calendar",
        "description": "For office meeting",
        "location": "344 Common st",
        "colorId": "8",
        "backgroundColor": "#16a765",
        "foregroundColor": "#000000",
        "accessRole": "owner",
        "defaultReminders": [],
        "conferenceProperties": {
            "allowedConferenceSolutionTypes": [
                "hangoutsMeet"
            ]
        }
    },
{
        "kind": "calendar#calendarListEntry",
        "etag": "\"1483552200690000\"",
        "id": "xxx.com_asae@group.calendar.google.com",
        "summary": "My office calendar",
        "description": "For office meeting",
        "location": "344 Common st",
        "colorId": "8",
        "backgroundColor": "#16a765",
        "foregroundColor": "#000000",
        "accessRole": "owner",
        "defaultReminders": [],
        "conferenceProperties": {
            "allowedConferenceSolutionTypes": [
                "hangoutsMeet"
            ]
        }
    }]

这就是我要结束的事情

[{
    "id": "xxx.com_asae@group.calendar.google.com",
    "title": "My office calendar",
}]

这样做的目的是我想使用Selectize插件填充一个选择框

3 个答案:

答案 0 :(得分:1)

您可以使用select方法过滤所需的键:

responde = {your_json_response}
expected = [response[0].select{|k,v| ['id','title'].include?(k)}]

response[0]检索散列,然后select将每个键与所需键进行比较,并仅返回具有以下键的散列:值对。

编辑:我想念您在原始回复上没有“ title”键,那么我会这样做:

response = {your_json_response}
h = response[0]
expected = [{'id' => h['id'], 'title' => h['summary']}]

编辑2:对不起,第一个示例不清楚是否会有多个散列

expected = response.map{|h| {'id' => h['id'], 'title' => h['summary']}}

map遍历response的每个元素,并以数组的形式返回应用于每次迭代的块的结果,因此这些块将被附加到每个h并生成一个新的从中散列

答案 1 :(得分:1)

另一种实现删除哈希中某些键的方法是使用Hash#reject方法:

response = { your_json_response }
expected = [response[0].reject {|k| k != :id && k != :summary}] 

返回原始响应的变异副本时,原始响应保持不变。

答案 2 :(得分:0)

我建议采用这种方法。

expected = response.each { |h| h.keep_if { |k, _| k == :id || k == :summary } }

它仅返回所需的对:

# => [{:id=>"xxx.com_asae@group.calendar.google.com", :summary=>"My office calendar"}, {:id=>"xxx.com_asae@group.calendar.google.com", :summary=>"My office calendar"}]

要删除重复项,只需执行expected.uniq

如果您需要将密钥名称:summary更改为:title,请执行以下操作:

expected = expected.each { |h| h[:title] = h.delete(:summary) }

一支班轮

expected = response.each { |h| h.keep_if { |k, _| k == :id || k == :summary } }.each { |h| h[:title] = h.delete(:summary) }.uniq

当然,也许最好将.uniq作为第一种方法expected = response.uniq.each { .....