Ruby Array to JavaScript Array

Ruby array to Javascript array

Let's assume you are using erb. A first approach:

<%= javascript_tag "account_ids = #{account_ids.to_json.html_safe};" %>

The problem is that this creates a global variable without context (who uses it?). That's why I'd rather call a function defined somewhere in your JS code:

<%= javascript_tag "setAccounts(#{account_ids.to_json.html_safe});" %>

Converting ruby array to javascript array not working properly

The to_json method returns a string that includes the array brackets. Therefore this should work:

var js_array =  <%= @qs.to_json %>;

Ruby array to js array in .js.erb file on rails

I assume, you are gettings @keys data from db or local. Could you try gon gem to pass the values from ruby to js. Here is the railscast tutorial for the same: http://railscasts.com/episodes/324-passing-data-to-javascript?view=asciicast

And see, if that works.

Let me know.

ruby array to javascript - Rails

var array = <%= escape_javascript @publisher_list.to_json %>

how to render Ruby array as JavaScript array in ERB template

Why don't your just use to_json?

# in ruby
@array = [{:text=>"Lorem", :weight=>15}, {:text=>"Ipsum", :weight=>15}]

Then, in the view:

var wordArray = <%= @array.to_json.html_safe %>;

Which will render:

var wordArray = [{"text":"Lorem","weight":15},{"text":"Ipsum","weight":15}];

Rails 3 passing a rails array to javascript function which uses a javascript array

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.

From Ruby array to JS array in Rails- 'quote'?

Try:

<%= raw @location_list.as_json %>

Using to_json will end up rendering a string, with embedded double-quotes, and would need to be JS-escaped. And it would be a string, not an array.

is there an equivalent of the ruby any method in javascript?

You are looking for the Array.prototype.some method:

var match = arr.some(function(w) {
return w.indexOf('z') > -1;
});

In ES6:

const match = arr.some(w => w.indexOf('z') > -1);


Related Topics



Leave a reply



Submit