我有一个数组:
[{
"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
来实现这一点?
最佳答案
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"}]
关于ruby-on-rails - 从键创建新的数组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39509481/