I have a ruby hash that i want to convert into a specific javascript hash.
Here is the ruby hash keyval
{
"Former Administration / Neutral"=>24,
"Media Personality / P"=>2,
"Journalist / Neutral"=>32,
"Consultant / Neutral"=>2,
...
"Journalist / P"=>11,
"Expert / Neutral"=>1,
"Activist / Neutral"=>15
}
Into javascript hash
{data: "Former Administration / Neutral", frequency: (24) },
{data: "Media Personality / P", frequency: (2) },
{data: "Journalist / Neutral", frequency: (32) },
{data: "Consultant / Neutral", frequency: (2) },
...
{data: "Journalist / P", frequency: (11) },
{data: "Expert / Neutral", frequency: (1) },
{data: "Activist / Neutral", frequency: (15) }
Tried
var obj = {};
for (var i = 0; i < <%= keyval.size %>; i++) {
obj["data"] = <%= keyval.keys[i] %>;
obj["frequency"] = '(' + <%= @keyval.values[i] %> + ')';
}
But the loop is not working obj return the first element of the ruby hash frequency=24 and does not escape the space in Former Administration. Why?
iis a JS variable, but you are trying to use it in the RoR code. And you are overwriting the same object in every cycle of the loop. You need a Ruby loop, not a JavaScript loop.