20

I have a Ruby hash which is passed to a hidden field. How do I extract this hash into JavaScript arrays that I can work with? I need to access the key/value pairs in JavaScript.

2 Answers 2

30

Ruby code:

state = { 'Waiting' => { name: 'Waiting now', color: 'btn-default' },
'Trying' => { name: 'Trying now', color: 'btn-danger' },
'Answered' => { name: 'Answered now', color: 'btn-success' } }

javascript code:

var state = JSON.parse('#{raw(state.to_json)}');
Sign up to request clarification or add additional context in comments.

1 Comment

Note, the single quotes are important because the to_json method creates a JSON string with embedded double quotes. Here is the form I used in my situation, where the javascript was in an embedded Ruby file (filename.html.erb): var data = JSON.parse('<%= raw(@contacts_list.to_json) %>');
18

Use my_awesome_ruby_hash.to_json and then you can simply either eval it in js or use parseJSON. You might need to require 'json' (not in Rails).

11 Comments

thanks, that works. how would i iterate through the result in the js code? i.e. the key/value pairs...does json return a js hash?
{ "a" => [1,2,3] } will turn into { "a" : [1,2,3]} so you can do obj["a"] in js to get it or a for in loop.
@jakub Hampl - i have this: myList = Hash.new() myList[var1] = const1 myList[var2] = const2 I set a variable in my controller as follows: @myHash = myList.to_json In my javascript, I get the value as follows: theList = JSON.parse($('#hiddenfield').attr('value')); for (key in theList) { alert("key "+key); alert(theList[key]); alert(theList[thelist(key)]); } Alert1 is "key0", Alert2 is "var1", Alert3 is "undefined". I can't seem to access the value per key. Any suggestions?
for (key in object) { if (!object.hasOwnProperty(key)) continue; value = object[key]; } should do the trick.
it still doesn't work, just returns the index e.g. 0 and the var1 as above
|

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.