我有这段代码(我将把它作为高图JS的JSON数据传递)
git push origin HEAD:development
返回:
<%= ItemSale.pluck(:item_id).uniq.map{|item_id| {
name: Item.find(item_id).name,
data: @item_sales.where(item_id: item_id).group_by_day(:date_sold,
format: "%s").count.to_a}}.to_json %>
但是,我需要这个:
[{"name":"Computer","data":[["1456790400",2],["1456876800",0],["1456963200",1]]},{"name":"Android Phones","data":[["1456876800",3],["1456963200",0],["1457049600",1],["1457136000",0],["1457222400",0],["1457308800",2]]}]
是一个整数并乘以1000,如下所示:
["1457049600",1]
我尝试过做样本数据以确保它是正确的并且正在运行:
[1457049600000,1]
是否有可能或有办法
@item_sales_series = [{"name":"Computer","data":[[1456790400000,2],[1456876800000,0],[1456963200000,1]]},{"name":"Android Phones","data":[[1456876800000,3],[1456963200000,0],[1457049600000,1],[1457136000000,0],[1457222400000,0],[1457308800000,2]]}].to_json
输出整数而不是字符串,并将它乘以1000?
我使用group date gem按日期对数据进行分组。此外,我没有在这个项目中使用Highchart gems,我正在尝试将数据插入图表的不同方法。
答案 0 :(得分:2)
>> array = [{"name":"Computer","data":[["1456790400",2],["1456876800",0],["1456963200",1]]},{"name":"Android Phones","data":[["1456876800",3],["1456963200",0],["1457049600",1],["1457136000",0],["1457222400",0],["1457308800",2]]}]
>> array.map{|hash| hash.merge(data: hash[:data].map{|str, int| [str.to_i*1000, int]})}
=> [{:name=>"Computer", :data=>[[1456790400000, 2], [1456876800000, 0], [1456963200000, 1]]}, {:name=>"Android Phones", :data=>[[1456876800000, 3], [1456963200000, 0], [1457049600000, 1], [1457136000000, 0], [1457222400000, 0], [1457308800000, 2]]}]
其工作原理如下:
# ,-- Loop over every element of the top-level array and change it's value
# | ,-- For each hash, change only the element called "data"
# | | ,-- In the "data" array, change every element
# | | | ,-- Change the string to an integer and multiply by 1000
# | | | |
# v v v v
>> array.map{|hash| hash.merge(data: hash[:data].map{|str, int| [str.to_i*1000, int]})}