如果密钥根据发出的GET请求动态更改,则从json对象获取密钥

时间:2018-05-16 19:04:36

标签: javascript jquery

HTML:

<select id="crypto_list">
    <option value="BTC">BTC</option>
    <option value="ETH">ETH</option>
    <option value="LTC">LTC</option>
    <!-- If Other is chosen, then use text box to type in symbol  -->
    <option value="other_crypto" id="other_crypto">Other</option>
</select>
<!--  -->
<select id="currency_list">
    <option value="USD">USD</option>
    <option value="EUR">EUR</option>
    <option value="INR">INR</option>
    <!-- If Other is chosen, then use text box to type in symbol  -->
    <option value="other_currency" id="other_currency">Other</option>
</select>

JavaScript是:

$.ajax({
        type: "GET",
        url: url_final,
        data: "json",
        success: function(response){
            var price = response.USD;
            //
            if($("#crypto_list").val() == "other_crypto" && $("#currency_list").val() == "other_currency"){
                document.querySelector("#value_of_crypto_in_real_currency").innerHTML = "<h2>Price of " + typed_value_1 + " is " + price + " " + typed_value_2 +  "!</h2>";
            }
            else{
                document.querySelector("#value_of_crypto_in_real_currency").innerHTML = "<h2>Price of " + url_2 + " is " + price + " " + url_4 + "!</h2>";
            }
        },
        error: function(error){
            alert("There is an error");
        }
    });
});

响应是一个JSON对象:

{"USD":8285.83}

如果我的JSON对象的Key(在这种情况下是USD)不断变化,我将如何获得该值。例如,我可以要求回复为欧元。但是我没有手动将我的价格变量更改为(response.EURO),而是想在我的下拉列表的onClick之后动态地执行此操作。有什么建议吗?

2 个答案:

答案 0 :(得分:0)

使用Object.keys,您可以获取对象的所有键,然后您可以使用第一个键,并使用它来获取价格。

var currency = Object.keys(response)[0];
var price = response[currency];

答案 1 :(得分:0)

您可以使用Object.keys,然后将数组映射到值,例如:

var price = Object.keys(response).map(key => response[key)[0];

如果我可能会建议另一项更改

以下代码:

if($("#crypto_list").val() == "other_crypto" && $("#currency_list").val() == "other_currency"){
    document.querySelector("#value_of_crypto_in_real_currency").innerHTML = "<h2>Price of " + typed_value_1 + " is " + price + " " + typed_value_2 +  "!</h2>";
}
else {
    document.querySelector("#value_of_crypto_in_real_currency").innerHTML = "<h2>Price of " + url_2 + " is " + price + " " + url_4 + "!</h2>";
 }

可能看起来更像这样:

document.querySelector("#value_of_crypto_in_real_currency").innerHTML =
  $("#crypto_list").val() == "other_crypto" &&
  $("#currency_list").val() == "other_currency"
    ? "<h2>Price of " + typed_value_1 +" is " +price +" " +typed_value_2 +"!</h2>"
    : "<h2>Price of " + url_2 + " is " + price + " " + url_4 + "!</h2>";