我需要构建一个对象数组,在显示过去7天数据的图表上显示数据有时数据库中会缺少某些7天记录,因此我需要显示该记录并将该值标记为0,以便在数组中有7个对象。
现在我有

[
  {
    "date": "2016-05-14",
    "amount": 6000
  },
  {
    "date": "2016-05-12",
    "amount": 12000
  }
]

我想要的是
[
    {
        "date": "2016-05-14",
        "amount": 6000
    },
    {
        "date": "2016-05-13",
        "amount": 0
    },
    {
        "date": "2016-05-12",
        "amount": 12000
    },
    {
        "date": "2016-05-11",
        "amount": 0
    },
    {
        "date": "2016-05-10",
        "amount": 0
    },
    {
        "date": "2016-05-09",
        "amount": 0
    },
    {
        "date": "2016-05-09",
        "amount": 0
    }
]

最佳答案

ts = JSON.parse '[
{
  "date": "2016-05-14",
  "amount": 6000
},
{
  "date": "2016-05-12",
  "amount": 12000
}]' # support ruby < 2.2

((Date.today-6..Date.today).map do |d|
  [d.iso8601, {'amount' => 0, 'date' => d.iso8601 }]
end.to_h.merge ts.group_by { |e| e['date'] }).values.flatten

在这里,我们先将一个请求的哈希值映射到零值,然后将其与现有值的哈希值合并。后者优先:
[Date.today].map do |d|
  [d.iso8601, {'amount' => 0, 'date' => d.iso8601 }]
end.to_h
#⇒ { '2016-05-16' => {'amount' => 0, 'date' => '2016-05-16' } }

(在真正的散列中有七项。)
Enumerable#group_by产生相同的结构:
[ {'amount' => 42, 'date' => Date.today } ].group_by { |e| e['date'] }
#⇒ { '2016-05-16' => [{'amount' => 42, 'date' => '2016-05-16' }] }

作为最后一步,我们将后者合并到前者中,并通过对结果进行values并将其展平来去掉日期键。
使用Hash#default_proc
hsh = Hash.new do |h, k|
  ts.detect do |e|
    e['date'] == k.iso8601
  end || { 'amount' => 0, 'date' => k.iso8601 }
end
(Date.today-6..Date.today).map { |d| hsh[d] }

关于ruby-on-rails - 过去7天遍历Date,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37247188/

10-11 06:22