我有一个数组:
[{
"name": "Category 1",
"entries": [{
"question": "Question 1",
"answer": "Answer 1"
}, {
"question": "Question 2",
"answer": "Answer 2"
}, {
"question": "Question 3",
"answer": "Answer 3"
}]
}, {
"name": "Category 2",
"entries": [{
"question": "Question 1",
"answer": "Answer 1"
}, {
"question": "Question 2",
"answer": "Answer 2"
}, {
"question": "Question 3",
"answer": "Answer 3"
}]
}]
我想要做的是创建一个仅包含条目的新数组。
所以我最终得到了这个:
[{
"question": "Question 1",
"answer": "Answer 1"
}, {
"question": "Question 2",
"answer": "Answer 2"
}, {
"question": "Question 3",
"answer": "Answer 3"
}, {
"question": "Question 1",
"answer": "Answer 1"
}, {
"question": "Question 2",
"answer": "Answer 2"
}, {
"question": "Question 3",
"answer": "Answer 3"
}]
在PHP中我只想推进一个新数组......但是在Ruby中可以使用group_by
或collect
来实现这个目标吗?
答案 0 :(得分:7)
array = [{
"name": "Category 1",
"entries": [{
"question": "Question 1",
"answer": "Answer 1"
}, {
"question": "Question 2",
"answer": "Answer 2"
}, {
"question": "Question 3",
"answer": "Answer 3"
}]
}, {
"name": "Category 2",
"entries": [{
"question": "Question 1",
"answer": "Answer 1"
}, {
"question": "Question 2",
"answer": "Answer 2"
}, {
"question": "Question 3",
"answer": "Answer 3"
}]
}]
array.flat_map { |hash| hash[:entries] }
#=> [{:question=>"Question 1", :answer=>"Answer 1"},
# {:question=>"Question 2", :answer=>"Answer 2"},
# {:question=>"Question 3", :answer=>"Answer 3"},
# {:question=>"Question 1", :answer=>"Answer 1"},
# {:question=>"Question 2", :answer=>"Answer 2"},
# {:question=>"Question 3", :answer=>"Answer 3"}]
答案 1 :(得分:1)
your_array.map {|hash| hash[:entries]}.flatten
#=> [{:question=>"Question 1", :answer=>"Answer 1"},
# {:question=>"Question 2", :answer=>"Answer 2"},
# {:question=>"Question 3", :answer=>"Answer 3"},
# {:question=>"Question 1", :answer=>"Answer 1"},
# {:question=>"Question 2", :answer=>"Answer 2"},
# {:question=>"Question 3", :answer=>"Answer 3"}]