我正在尝试实现以下JSON结果:
{
"movie" =>
[{
"title": "Thor",
"year" : 2011,
},
{
"title": "Iron Man",
"year" : 2008,
}],
"tv" =>
[{
"title": "Parks and Recreation"
"year": 2009
},
{
"title": "Friends"
"year": 1994
}]
}
使用JavaScript,我会遍历我的结果并执行以下操作:
results['movie'].push(item);
results['tv'].push(item);
使用Ruby代码,我离开的最远的是:
@results = Hash.new
results['Search'].each do |r|
if r['Type'] == 'movie'
@results['movie'] << {
'title' => r['Title'],
'year' => r['Year']
}
elsif r['Type'] == 'series'
@results['tv'] << {
'title' => r['Title'],
'year' => r['Year']
}
end
end
我在这里错过了什么?
我认为问题与哈希的初始化有关。 movie
和tv
键目前不是数组。您可以像这样初始化哈希:
@results = { 'movie' => [], 'tv' => [] }
以下是其余代码的外观:
@results = { 'movie' => [], 'tv' => [] }
results['Search'].each do |r|
if r['Type'] == 'movie'
@results['movie'] << {
'title' => r['Title'],
'year' => r['Year']
}
elsif r['Type'] == 'series'
@results['tv'] << {
'title' => r['Title'],
'year' => r['Year']
}
end
end
我认为你可以通过使用Enumerable#each_with_object
并为哈希值分配默认值来获得你想要的东西。
def group_search_results(items)
results = Hash.new { |hash, key| hash[key] = [] }
items.each_with_object(results) do |item|
results[item['Type']] << {'title' => item['Title'], 'year' => item['Year']}
end
end
describe "search_results" do
it "groups into an object" do
items = [
{'Type' => 'movie', 'Title' => 'Thor', 'Year' => 2011},
{'Type' => 'movie', 'Title' => 'Iron Man', 'Year' => 2008},
{'Type' => 'series', 'Title' => 'Parks and Recreation', 'Year' => 2009},
{'Type' => 'series', 'Title' => 'Friends', 'Year' => 1994},
]
results = group_search_results(items)
expect(results).to eq({
'movie' => [
{'title' => 'Thor', 'year' => 2011},
{'title' => 'Iron Man', 'year' => 2008},
],
'series' => [
{'title' => 'Parks and Recreation', 'year' => 2009},
{'title' => 'Friends', 'year' => 1994},
],
})
end
end
results = {
search: {
movie: [
{ title: 'Thor', year: 2011 },
{ title: 'Iron Man', year: 2008 },
],
tv: [
{ title: 'Parks and Recreation', year: 2009 },
{ title: 'Friends', year: 1994 },
]
}
}
@results = Hash.new{|k, v| k[v] = []}
results[:search].each do |type, array|
@results[type].push(*array)
end
results[:search].each_with_object(Hash.new{|k, v| k[v] = []}) do |(type, array), hash|
hash[type].push(*array)
end