Recently, I encountered a scenario in my application where I needed to pass an Array of elements from my controller to a Javascript view. The goal was to convert this Array into JSON format and then parse it.
In the View section of my code, I included the following snippet:
<% content_for :page_meta do %>
<script>
const filterItems = "<%= @filter_options %>";
const productItems = "<%= @mdms_products %>";
</script>
Upon debugging the @filter_options in IRB, I found that its class is Array and it contained the following data:
[{:name=>"Solution Type", :uid=>"application", :component=>"HierarchicalListFilter", :props=>{:rootUrl=>"/insulation/commercial/enclosure/applications", :rootText=>"Enclosure Solutions"}, :values=>[{:name=>"Walls", :slug=>"walls",
At first glance, everything seemed fine. However, upon checking my javascript console for the value of productItems, I noticed that the output was distorted with characters like " and >. This made parsing difficult as I encountered errors.
Therefore, I am seeking advice on a better approach to seamlessly pass a Ruby Array to a JavaScript JSON format. Any suggestions would be greatly appreciated.