简体   繁体   中英

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 ?

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.ya 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 <%= %>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM