Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails hash of hashes in Javascript

i have a hash of hashes in rails, like :

{"round"=>1, "turn"=>1, "attacker_hp"=>11220, "defender_hp"=>205, "damage"=>95, "attacker"=>#<User id: 2, email:...>}, {"round"=>1, "turn"=>2, "attacker_hp"=>11220, "defender_hp"=>205, "damage"=>95, "attacker"=>#<User id: 1, email:...>} ...

So, as you can see, in this hash, there is a number of hashes that represent a combat turn. There is also a hash entry that contains a full object.attributes in it (the 'attacker' entry').

Now, i want to represent that using JQuery in Rails. I've tried to use something like :

var combat_stats = <%= array_or_string_for_javascript(@combat) %>;

to get the values in Javascript. This works, but there is an important problem. It seems that it creates an array of strings. Thus, the internal hashes are now strings, which makes it impossible for me to parse in javascript.

My question is, how can i access values like :

turn['attacker']['name'] or turn['attacker_hp']

as i could easily do in a @combat.each loop inside Rails view ?

like image 553
Spyros Avatar asked Jun 07 '11 22:06

Spyros


2 Answers

Are you familiar with JSON structure? You can use @combat.to_json and then work with the json instead of an array.

With that you can easily access values as you do in rails, for example:

var foo = {
  bar: 1,
  x: [1, 2, 3],
  y: {
    a: "string"
  }
}

foo.bar or foo["bar"] will return 1

foo.x will return array [1,2,3]

foo.y.a will return "string"

etc...

Edit:

Maybe you will need to use @combat.to_json.html_safe as it should be html parsed when you use <%= %>

like image 87
Bernardo Mendes Avatar answered Oct 04 '22 20:10

Bernardo Mendes


console.log(JSON.parse('<%= @link.errors.messages.to_json.html_safe%>'))  

returns object
so

JSON.parse('<%= @link.errors.messages.to_json.html_safe%>')  

may be used as js object

like image 34
antiqe Avatar answered Oct 04 '22 19:10

antiqe