nehel nehel - 4 months ago 22
jQuery Question

convert temperature in json

How do I put value from

input
(that is dynamically changing) in a
json
object to convert i.e
K
to
C
? Or how should I actually write such conversion if my thoughts are bad?

The way I am thinking is (i.e
K
to
C
):



var quantities= [
{
'name': 'Temperature',
'properties': [
{
'name': 'Kelwin',
'symbol': 'K',
'units': {
'K': 1,
'C': 'inputValue + 273.15',
'F': '(inputValue + 459.67)*5/9'
}
},
{
'name': 'Celsius',
'symbol': 'C',
'units': {
'K': 'inputValue - 273.15',
'C': 1,
'F': '(inputValue - 32)*5/9'
}
},
{
'name': 'Fahrenheit',
'symbol': 'F',
'units': {
'K': 'inputValue * 9/5-459.67',
'C': 'inputValue * 9/5+32',
'F': 1
}
}
]
}
]

var optionsIndex = $('select.from option:selected').index();
var from = $('select.from option:selected').val();
var to = $('select.to option:selected').val();

var fromSelectTypeValue = quantities[0].properties[optionsIndex].units[from];
var toSelectTypeValue = quantities[0].properties[optionsIndex].units[to];

var result = fromSelectTypeValue * toSelectTypeValue;
//fromSelectType = 1 (because K is choosen in first select element)
//toSelectTypeValue = 'inputValue + 273.15' (because C is choosen in second select element)

var $inputs = $('.inputValue, select.from, select.to');
$inputs.on('keyup change', function () {
$('.result').val(result);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="inputValue" placeholder="Insert value" />
<br />
<select class="from">
<option value="K">Kelvin</option>
<option value="C">Celsius</option>
<option value="F">Fahrenheit</option>
</select>

<select class="to">
<option value="K">Kelvin</option>
<option value="C">Celsius</option>
<option value="F">Fahrenheit</option>
</select>
<br />

<input type="numer" class="result" placeholder="Result" readonly />




Answer

You've got this entirely the wrong way round - you dont put your value "dynamically into your JSON", you make your javascript configuration object able to deal with dynamic values.

For example, your conversaions should be actual functions, rather than textual representations of those functions (which are hard to "execute" safely).

var quantities= [
   {
        'name': 'Temperature',
        'properties': [
            {
                'name': 'Kelwin',
                'symbol': 'K',
                'units': {
                    'K': function(input){ return input; },
                    'C': function(input){ return input + 273.15; },
                    'F': function(input){ return (input + 459.67)*5/9; }
                }
            },
      ....

Then, assuming you know how to pull the right function out your object, you just execute the function:

var kToC = quantities[0].properties[0].units.C; // assume you know how to look this up
var c = kToC(123); // execute the function (convert 123 k to c)
Comments