I am trying to pass a rails array to a javascript function. The function will then use the array values in javascript so I need to keep it an array.
Here is how I am
bokor's answer works, but causes some linter and IDE errors if you want the array to be saved to a const
, instead of a var
/ let
.
The following variation seems to work and be compliant with the linters and IDEs that I am using.
const js_array = JSON.parse('<%= raw @object %>');
Going to JSON as suggested a couple times in this post always gave me something like this.
[{"mile":{"date":"2011-05-20","mpg":"18.565887006952"}},{"mile":{"date":"2011-06-01","mpg":"18.471164309032"}}]
What I really wanted was just this... [[2011-05-20, 18.56][2011-06-01, 18.47]]
So I handled it with a helper like so.
def chart_values()
@chart_values = '['
@mpg_values.each do |m|
@chart_values = @chart_values+'['+m.date.to_s+', '+m.mpg.round(2).to_s+'],'
end
@chart_values = @chart_values+']'
end
Then passed chart_values() to the javascript.
Likely not the best solution but it gave me the desired values in the format I needed.
If you're using HAML, you can just do this:
var js_array = #{object};
collect
Method.A cleaner version of your solution, Xaxum, would be something like this:
def chart_values
@mpg_values.collect do |mpg_value|
[ mpg_value.date.to_s, mpg_value.mpg.round(2).to_f ]
end
end
The collect
method automatically generates an array of whatever the block results in, so you'll end up with something like this:
[
[2011-05-20, 18.56],
[2011-06-01, 18.47]
]
I also changed the mpg
value to use to_f
, which provide a number instead of a string.
Since this still seems like an issue and nobody resolved it. Here goes
var js_array = [<%= raw @object.to_json %>];