我有这样一个数组:
array_hash = [
{
"array_value" => 1,
"other_values" => "whatever",
"inner_value" => [
{"iwantthis" => "forFirst"},
{"iwantthis2" => "forFirst2"},
{"iwantthis3" => "forFirst3"}
]
},
{
"array_value" => 2,
"other_values" => "whatever2",
"inner_value" => [
{"iwantthis" => "forSecond"},
{"iwantthis2" => "forSecond2"},
{"iwantthis3" => "forSecond3"}
]
},
]
我想把"inner_value"从这个数组中弹出到另一个数组中
所以我想为inner_value创建一个单独的数组,格式如下:
inner_value_array = [
{"iwantthis" => "forFirst"},
{"iwantthis2" => "forFirst2"},
{"iwantthis3" => "forFirst3"},
{"iwantthis" => "forSecond"},
{"iwantthis2" => "forSecond2"},
{"iwantthis3" => "forSecond3"}
]
现在我不需要原始array_hash中的inner_value,所以它可以被删除。所以原来的array_hash应该是这样的
array_hash = [
{
"array_value" => 1,
"other_values" => "whatever"
},
{
"array_value" => 2,
"other_values" => "whatever2"
},
]
我已经试过了:
inner_value_array = array_hash.collect{|d| d["inner_value"] }
对于100个值,它工作得很好,很快,但它没有删除inner_value,虽然我并不关心它是否被删除,但这会占用无用的内存,所以有没有一种有效的方法来从array_hash中弹出inner_value ?
您可以使用flat_map
array_hash.flat_map{ |k| k['inner_value'] }
#=> [{"iwantthis"=>"forFirst"}, {"iwantthis2"=>"forFirst2"}, {"iwantthis3"=>"forFirst3"}, {"iwantthis"=>"forSecond"}, {"iwantthis2"=>"forSecond2"}, {"iwantthis3"=>"forSecond3"}]
我能想到的最短的东西:
inner_value_array = array_hash.inject([]) {|result,h| result << h.delete("inner_value") }
only_inner = []
array_hash.each {|h| only_inner << h.delete('inner_value') } # Remove the inner value and store in the only_inner array
only_inner.flatten # Combine all inner values