Search code examples
javascriptjqueryconstants

Using a variable as part of a constant name in dot notation


I'm looking for a way to use the value from var opt = $("#select option:selected").val();, e.g., option1 and use that as part of a const variable in dot notation.

For example, I want to use the value of opt which has the value of option1 to call the value of price.option1.savings. I want opt to substitute for option` where {option1} is The result should be 11. Is there a way?

const price = {
      option1: {type: 'R-11', rValue: 11, savings: 0.20, pct: 0.12},
      option2: {type: 'R-13', rValue: 13, savings: 0.22, pct: 0.12},
      option3: {type: 'R-19', rValue: 19, savings: 0.24, pct: 0.12}
}

$(function() {
  $("#select").blur(function() {
    var opt = $("#select option:selected").val();
    var result = price.${!opt}.savings;
    $("#result").html(result);
  });
});
<select id="select" name="select">
  <option selected ></option>
  <option value="option1">R-11 Batt</option>
  <option value="option2">R-13 Batt</option>
  <option value="option3">R-19 Batt</option>
</select>
<div id="results">{results here}</div>

const price = {
    option1: {type: 'R-11', rValue: 11, savings: 0.20, pct: 0.12},
    option2: {type: 'R-13', rValue: 13, savings: 0.22, pct: 0.12},
    option3: {type: 'R-19', rValue: 19, savings: 0.24, pct: 0.12}
}

$(function() {
    $("#select").blur(function() {
        var opt = $("#select option:selected").val();
    var result = price.${!opt}.savings;
        $("#result").html(result);
    });
});

Solution

  • You would have to do something like this

    $(function() {
        $("#select").blur(function() {
            var opt = $("#select option:selected").val();
        var result = price[opt].savings; // we substituted ${!opt} to [opt]
            $("#result").html(result);
        });
    });
    

    Which from what I am aware is the only way to get properties of an object using a value of a variable. You can read more about it here