仅使用Hash #select和/或Array#select解析具有特定哈希值的数组

时间:2014-08-10 16:04:53

标签: ruby-on-rails ruby arrays json hash

如何使用Hash#select和/或Array#select仅解析包含products的{​​{1}}数组?

直播应用:http://runnable.com/U-eWKpORZ5A644gK/array-hash-select-for-ruby-on-rails(请参阅{ "name": "sale", "value": "true" }

main_controller.rb

2 个答案:

答案 0 :(得分:4)

使用select

myarr = [{ "name" => "sale", "value" => "true" }, { "name" => "test", "value" => "true"}]
myarr.select { |h| h["name"] == "sale" && h["value"] == "true" }
=> [{"name"=>"sale", "value"=>"true"}]

在你的情况下,你会得到一个Hash(在解析JSON之后),如下所示:

response = {"productHeader" => {"totalHits" => 32090}, "products" => [{ "name" => "sale", "value" => "true" }, { "name" => "test", "value" => "true"}]}

然后,您可以使用此代码:

response = JSON.parse(@json_text)

response["products"].select { |h| h["name"] == "sale" && h["value"] == "true" }.each do |filtered_response|
  # Do whatever you want with the filtered product
end

答案 1 :(得分:1)

即使使用mashie,这也可以。

@products = response['products'].select do |e|
  e.is_a? Hash \
  and (f = e['fields']).is_a? Array \
  and f.any? do |g|
    g.is_a? Hash \
    and g['name'] == 'sale' \
    and g['value'] == 'true'
  end
end

或尝试

@products = response['products'].select do |e|
  e.is_a? Hash \
  and (f = e['fields']).is_a? Array \
  and f.any? do |g|
    g.is_a? Hash \
    and g['name'] == 'sale' \
    and g['value'] == 'true'
  end
end.map{ |e| Hashie::Mash.new(e) }