如何检索与json中的名称相对应的随机值 [英] How to retrieve random values corresponding to the name in json
问题描述
这些是JSON中的键/值
These are the key/values in JSON
[
{
"country":"First",
"coupon":["1"]
},
{
"country":"First",
"coupon":["10"]
},
{
"country":"First",
"coupon":["12"]
},
{
"country":"Second",
"coupon":"2"
},
{
"country":"third",
"coupon":"3"
},
{
"country":"fourth",
"coupon":"4"
},
{
"country":"fifth",
"coupon":"5"
}
]
我整理了JSON中的重复项并显示在下拉列表中
I sorted out the duplicates in JSON and displayed on dropdown
var sortedCountries = [];
if (sortedCountries.indexOf(value.country) == -1) {
$('#sel').append('<option value="' + value.coupon + '">' + value.country + '</option>');
sortedCountries.push(value.country);
}
因此,当我在下拉列表中选择每个选项时,就会显示相应的值,即优惠券.但是,当我使用国家":第一"选择下拉菜单时,我需要生成随机值(优惠券),该怎么做?
So when I select each option in the dropdown the corresponding value i.e coupon appears. But I need to generate random values (coupons) when I select the dropdown with "country": "First", How to do that?
推荐答案
当我查看您引用的链接时,我看到:
When I review the link you referenced, I see:
http://www.thegameappstudio.com/watchface/json/thegasfitness.json
这将返回JSON数据,例如:
This return JSON data like:
[
{
"Application Title": "TheGas Fitness",
"Content ID": "000004891575",
"country": "Spain",
"coupon": "S8ZEUXL19GELB5RN",
"Usable Dates(GMT)": "2020-06-04 00:00",
"Expiration Date(GMT)": "2020-06-30 00:00",
"Remaining Days": 27,
"Coupon Status": "Not Used"
}
]
它使用以下代码:
$(document).ready(function() {
$('#sel').select2({
/* Sort data using lowercase comparison */
sorter: data => data.sort((a, b) => a.text.toLowerCase() > b.text.toLowerCase() ? 0 : -1)
});
var url = "http://www.thegameappstudio.com/watchface/json/thegasfitness.json";
$.getJSON(url, function(data) {
var myArray = new Array();
$.each(data, function(index, value) {
// APPEND OR INSERT DATA TO SELECT ELEMENT.
$('#sel').append('<option value="' + value.coupon + '">' + value.country + '</option>');
});
});
// SHOW SELECTED VALUE.
$('#sel').change(function() {
var str = $("#sel").val();
$("#txtName").val(str);
});
$("#cpy").click(function(event) {
var copyText = document.getElementById("txtName");
copyText.select();
copyText.setSelectionRange(0, 99999)
document.execCommand("copy");
alert("Copied Coupon Code: " + copyText.value);
});
});
所以最终的Select就像:
So the resulting Select is like:
<select id="sel">
<option value="S8ZEUXL19GELB5RN">Spain</option>
</select>
您的数据有很大的不同.在您的数据中,该值为整数.因此,在您的change
回调中,您需要将其作为索引发送到Coupon数组.
Your data is vastly different. In your Data, the value is a integer. So in your change
callback, you would need to send that as an Index to your Coupon Array.
$('#sel').change(function() {
var i = $("#sel").val();
$("#txtName").val(coupons[i]);
});
您需要一个包含字母数字优惠券的优惠券代码数组.
You would need an Array of Coupon codes, containing the Alphanumeric coupons.
这篇关于如何检索与json中的名称相对应的随机值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!