jquery - javascript: clean way of converting currencies from an array -



jquery - javascript: clean way of converting currencies from an array -

folks! have written below code, converts 1 currencies , problem defining each & every currencies 1 1 in switch block,

if have 100 currencies convert have write 100 switch cases there can create below code dynamic , short?

var currencies = {}; $(document).ready(function(){ yahoo_getdata(); }); function yahoo_getdata() { var = new date(); var b = "http://someapiurl.com/webservice/v1/symbols/allcurrencies/quote?format=json&random=" + a.gettime() + "&callback=?"; $.getjson(b, function (e) { if (e) { var i, l, r, c; r = e.list.resources; (i = 0, l = r.length; < l; += 1) { c = r[i].resource.fields; //console.log(c.name, c.price); switch (c.name) { case "usd/eur": currencies.eur = c.price; console.log('usd/eur = ' + c.price); break; case "usd/usd": currencies.usd = c.price; console.log('usd/usd = ' + c.price); break; case "usd/jpy": currencies.jpy = c.price; console.log('usd/jpy = ' + c.price); break; case "usd/inr": currencies.inr = c.price; console.log('usd/inr = ' + c.price); break; } } console.log(currencies); //console.log(e); //var d = {}; } }); } $("#amount1").keyup(function() { var usd, amount1 = $('#amount1').val(), currency1 = $("#currency1").val(), currency2 = $("#currency2").val(); // normalize usd usd = amount1 / currencies[currency1]; // convert target currency $('#amount2').val(usd * currencies[currency2]); });

use object maps currency name object property name:

var currency_map = { 'usd/eur': 'eur', 'usd/usd': 'usd', 'usd/jpy': 'jpy', ... };

then:

for (var = 0, l = r.length; < l; i++) { c = r[i].resource.fields; currencies[currency_map[c.name] || c.name] = c.price; console.log(c.name + ' = ' + c.price); }

fiddle

javascript jquery yahoo-finance

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -