Home > Mobile >  how do I grab a deeply nested value in ruby?
how do I grab a deeply nested value in ruby?

Time:09-13

so I am trying to filter invoices by their sale_id. there is a lot of information on an invoice and I need to grab the sale_id off of a hash inside of an array. I am filtering invoices by this value but have had trouble getting the correct result

I search for invoices from a specific store with invoices = store.invoices. this will return an array populated with hashes. here is apart of what I get for one hash:

  rows: [{"name"=>"sale 1", "item_id"=>1289, "sale_id"=>1413, "single_amount"=>"5000.0", "amount"=>"5000.0", "quantity"=>1, "charges_amount"=>"0.0", "tax_amount"=>"0.0", "tax_rate_id"=>nil, "total_amount"=>"5000.0"}],
  note: nil,
  total: 0.5e4,
  paid_total: 0.0,

i've tried: filtered = invoices.select { |i| i['sale_id'] == sale.id } but this just returns an empty array. I thought maybe I just needed to reach a level deeper so I tried invoices.select{|i| i['rows'][sale_id] == 1413} but I again get an empty result.

I also tried rows = invoices.map(&:rows), which will give me a nested array with hashes of rows from all the different invoices. but this doesn't help me much because I will ultimately need the individual invoice id after finding ones that are a match. I've been stuck on this for so long and feel like I'm missing a basic piece here and would love some insight. thanks!

CodePudding user response:

You need to get the first item in the rows array and then select sale_id

invoices.select { |i| i['rows'][0]['sale_id'] == sale.id }

You can also use dig to prevent error in case some key/values are missing.

invoices.select { |i| i.dig('rows', 0, 'sale_id') == sale.id }
  • Related