gpt4 book ai didi

ruby-on-rails - 从键创建新的数组数组

转载 作者:太空宇宙 更新时间:2023-11-03 17:09:47 24 4
gpt4 key购买 nike

我有一个数组:

[{
"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_bycollect 来实现这一点?

最佳答案

使用Enumerable#flat_map :

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com