I have an Array of Hashes returned from the below map function. I'm trying to populate data for a graph(I'm using AM charts), which takes data in a specific format mentioned below-
Sample Structure of a Company Record
1.9.3p327 :073 > Company
=> Company(id: integer, name: string, contact_no: integer, email_id: string, website: string, fax_no: integer, created_at: datetime, updated_at: datetime, divisions_count: integer)
@all_companies = Company.all
Map Function:
@all_companies = @all_companies.map {|each_company| { Country: each_company.name, Visits: each_company.divisions_count} }
Output Format of above query
[{:country=>"Samsung", :visits=>8}, {:country=>"Natraj", :visits=>2}, {:country=>"Tupperware", :visits=>5}, {:country=>"Transcen", :visits=>0}, {:country=>"camlin", :visits=>0}]
Graph Data Input Format:
var chartData = [{
country: "USA",
visits: 4025
}, {
country: "China",
visits: 1882
}, {
country: "Japan",
visits: 1809
}, {
country: "Germany",
visits: 1322
}]
I'm using Ruby 1.9.3-p327. I need to convert my output array to the specific graph format. . I try going about the same through the following steps:-
1.9.3p327 :070 > @all_companies = @all_companies.to_s.gsub(":","")
=> "[{country=>\"Samsung\", visits=>8}, {country=>\"Natraj\", visits=>2}, {country=>\"Tupperware\", visits=>5}, {country=>\"Transcen\", visits=>0}, {country=>\"camlin\", visits=>0}]"
1.9.3p327 :071 > @all_companies = @all_companies.gsub("=>",": ")
=> "[{country: \"Samsung\", visits: 8}, {country: \"Natraj\", visits: 2}, {country: \"Tupperware\", visits: 5}, {country: \"Transcen\", visits: 0}, {country: \"camlin\", visits: 0}]"
1.9.3p327 :072 > puts @all_companies
[{country: "Samsung", visits: 8}, {country: "Natraj", visits: 2}, {country: "Tupperware", visits: 5}, {country: "Transcen", visits: 0}, {country: "camlin", visits: 0}]
=> nil
1.9.3p327 :073 >
Now when I'm trying to display the data in my graph, I'm getting the below Syntax error:-
var chartData = [{country: "Samsung", visits: 8}, {country: "Natraj", visits: 2}, {country: "Tupperware", visits: 5}, {country: "Transcen", visits: 0}, {country: "camlin", visits: 0}]
The syntax error from the firebug console now points to " in the above data.
Any work arounds that could help me get through the last step so that I can get the desired graph format?
Question Updated
I need the Data in following format :-
var chartData = [
{
country: "Samsung",
visits: 8
},
{
country: "Natraj",
visits: 2
},
{
country: "Tupperware",
visits: 5
},
{
country: "Transcen",
visits: 0
},
{
country: "camlin",
visits: 0
}
]
Thank you.