15

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 ?

2 Answers 2

22

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

Sign up to request clarification or add additional context in comments.

2 Comments

And #to_json's output is almost always objects or arrays, as @spyrosP would like. +1
aaa, great idae thanx that saves the day !
6
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.