我需要从嵌套的哈希数组中检索一些值,如下所示:
{:id=>1, :field_id=>200, :name=>"01", :midpoint=>{:lat=>"37.716801", :lng=>"-120.604216"}}
{:id=>2, :field_id=>201, :name=>"02", :midpoint=>{:lat=>"37.717551", :lng=>"-120.608567"}}
{:id=>3, :field_id=>202, :name=>"03", :midpoint=>{:lat=>"37.714297", :lng=>"-120.612967"}}
{:id=>4, :field_id=>203, :name=>"04", :midpoint=>{:lat=>"37.714591", :lng=>"-120.615368"}}
{:id=>5, :field_id=>204, :name=>"05", :midpoint=>{:lat=>"37.710421", :lng=>"-120.616498"}}
我可以使用hash.map()获取一个键的值数组,如下所示:
idArray = inputHash.map { |k| k[:id]}
但是我想得到(哈希)[:name]和[:id]。像这样:
{:id=>1, :field_id=>200}
{:id=>2, :field_id=>201}
{:id=>3, :field_id=>202}
{:id=>4, :field_id=>203}
{:id=>5, :field_id=>204}
答案 0 :(得分:2)
尝试 -
idArray = inputHash.map { |k| {:id => k[:id], :field_id => k[:field_id]}}
答案 1 :(得分:0)
你应该这样做:
array_of_hash.collect { |h| { id: h[:id], field_id: h[:field_id] } }