I am trying to send slightly complicated from my Rails app through JSON to a JS script to render the page in some interesting manner. Let us say the data in Rails is about people and their assets and looks like this:
[
{:name => 'Bill Smith', :state => 'KS'} => [
{:type => 'house', :valuation => 150000},
{:type => 'car', :valuation => 10000}
],
{:name => 'Bubba Jack', :state => 'FL'} => [
{:type => 'boat', :valuation => 12000}
]
]
On the JS side, I want to be able to access the individual fields, However, JS doesn’t allow the keys of objects to be objects, so data.to_json converts all the person details into one string like this:
[{"{:name=>\"Bill Smith\", :state=>\"KS\"}":[{"type":"house","valuation":150000},{"type":"car","valuation":10000}],"{:name=>\"Bubba Jack\", :state=>\"FL\"}":[{"type":"boat","valuation":12000}]}]
I can’t do stuff like
var people = Object.keys(data);
for(var i=0; i<people.length; i++) {
var totAsset = 0;
var person = people[i];
for(var j=0;j<data[person].length; j++) {
totAssset = totAsset + data[person][j].valuation
}
alert("got person named " +person.name+" having $"+totAsset);
}
What is the ‘right’ way to represent and use complex data on the JS side of an AJAX app?
Update: So both sgrif and Andrew’s answers provide a solution to this particular problem. I’ve upvoted both of them, but I’ll wait a few to see if there is a more general idea someone has to represent objects as keys or something with that functionality before accepting.
Wouldn’t it be easier to organize your records as such:
Then use “render :json => @people”, which will give you.
Then access the values as such.