简体   繁体   中英

Rails Hash in javascript, access values

I have a following javascript code:

<input type="hidden" name="query_form_select_ops" id="query_form_select_ops" value='<%= schema%>'  />

<script>
  function select_pk2(cell){
  var val = $('#query_form_opt_'+cell+'_1').val();
  var opts = $('#query_form_select_ops').val();  
  }
</script>

Example:

schema is a typical ruby hash:

{ 
  "car"=>{"col"=>"blue", "engine"=>"HHd4M"},
  "train"=>{"col"=>"black", "engine"=>"8495f"}
}

The variable val has a value "train" and opts the whole ruby hash

To access the col and engine of a train in ruby: schema["train"]. How can I do the same in javascript?
I have tried:

var select = opts[val]

but it tells me that var in undefined. How can I access the values of a ruby hash in javascript given a hash and one of the keys?

Dump schema hash as a json and then parse it back in javascript. Something like this:

<input type="hidden" name="query_form_select_ops" id="query_form_select_ops" value='<%= schema.to_json %>'  />

And script:

function select_pk2(cell){
  var val = $('#query_form_opt_'+cell+'_1').val();
  var opts = JSON.parse($('#query_form_select_ops').val());  
}

This way you should be able to access values in the way you want.

Each individual value of the hash in your example is hash as well, so you can access them by using proper keys. Like this:

opts['car']['col'];

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