0

I have array for exchange rate currencies:

var mainCCexArr = [{EUR: 0.80 , GBP: 3.50}];

how do i alert array value by key?

for instant - i need value for key "GBP" -> 3.5

Can i do it without array LOOP (for, while, etc) ?

HTML:

<select name="def_cc">
    <option value="GBP">UK</option>
    <option value="USD">USD Dollar</option>                         
</select>

I tries this:

  var def_cc_code = $('select[name="def_cc"] option:selected').val();
  var ex_cc = mainCCexArr[def_cc_code].value;

  alert("ex_cc: " + ex_cc);

Thank you in advance

roi
  • 73
  • 1
  • 6
  • You currently (see what I did there) have an "array" with only one entry - are there more entries in the array? Are you trying to get out just GBP for the first entry? Is there a reason you can't use *any* form of loop (eg `.map()` can be considered a loop). Did you mean for it to be in an array? Can you provide a more detailed example with other array entries and what you want out when there's more entries? – freedomn-m Aug 21 '20 at 16:26
  • `var ex_cc = mainCCexArr[0][def_cc_code]` - of course, it will only work if you match the keys (`"GBP" !== "GPB"`) https://jsfiddle.net/de4bnks8/ – freedomn-m Aug 21 '20 at 16:26
  • 2
    Does this answer your question? [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) or https://stackoverflow.com/questions/4255472/javascript-object-access-variable-property-by-name-as-string (or any of the other linked questions) – freedomn-m Aug 21 '20 at 16:29
  • @freedomn-m - i see what you did, and it's working in your example, but in mine i have a little change and it doesn't works. `var def_cc_code = $('select[name="def_cc"] option:selected').val();` – roi Aug 21 '20 at 16:39
  • Works fine: https://jsfiddle.net/sg1ahmet/2/ of course I had to add USD to the array – freedomn-m Aug 21 '20 at 16:50

1 Answers1

0

var mainCCexArr = {USD: 0.80 , GBP: 3.50};
$('select').on('change', function(){
  var select_val = $(this).val();
  alert(mainCCexArr[select_val]);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="def_cc">
    <option value="">Select Value</option>
    <option value="GBP">UK</option>
    <option value="USD">USD Dollar</option>                         
</select>
Shehbaz Badi
  • 19
  • 1
  • 3