我有一个很大的JSON数组,可以在这里找到。 我想按照用户在输入字段中输入的值对这些数据进行排序,并将其保存到一个变量中。
null
function submit() {
let inputValue = document.getElementById("input").value;
fetch("https://api.covid19api.com/summary")
.then(res => res.json())
.then(data => {
//code for sorting countries goes here
})
}
<input id="input" placeholder="Country Name">
<button onclick="submit()">Submit</button>
null
同样,我想在这里做的是让用户在输入字段中输入国家的名称,例如,印度。 在submit函数中,我想要获取数据并按照注释所示对其进行排序。 然后,这些排序后的数据将以数组形式存储在另一个数组中。 如何执行此操作?
基本上我想要的是当用户搜索一个国家时,例如,印度,印度的数据存储在一个变量中。
null
var userInput = [{
"Country": "India",
"CountryCode": "IN",
"Slug": "india",
"NewConfirmed": 9471,
"TotalConfirmed": 236184,
"NewDeaths": 286,
"TotalDeaths": 6649,
"NewRecovered": 4783,
"TotalRecovered": 113233,
"Date": "2020-06-06T14:58:35Z"
}]
null
你可以这么做。 根据输入值确定选择国家的优先次序:
null
var data = {
"Global": {
"NewConfirmed": 101781,
"TotalConfirmed": 6829314,
"NewDeaths": 3800,
"TotalDeaths": 402636,
"NewRecovered": 131192,
"TotalRecovered": 3000504
},
"Countries": [
{
"Country": "Afghanistan",
"CountryCode": "AF",
"Slug": "afghanistan",
"NewConfirmed": 915,
"TotalConfirmed": 18969,
"NewDeaths": 9,
"TotalDeaths": 309,
"NewRecovered": 177,
"TotalRecovered": 1762,
"Date": "2020-06-06T14:38:12Z"
},
{
"Country": "Albania",
"CountryCode": "AL",
"Slug": "albania",
"NewConfirmed": 15,
"TotalConfirmed": 1212,
"NewDeaths": 0,
"TotalDeaths": 33,
"NewRecovered": 12,
"TotalRecovered": 910,
"Date": "2020-06-06T14:38:12Z"
},
{
"Country": "Algeria",
"CountryCode": "DZ",
"Slug": "algeria",
"NewConfirmed": 104,
"TotalConfirmed": 9935,
"NewDeaths": 9,
"TotalDeaths": 690,
"NewRecovered": 156,
"TotalRecovered": 6453,
"Date": "2020-06-06T14:38:12Z"
}
]
};
var inputValue = "Algeria"
data.Countries.sort((a,b)=>{
if(a.Country === inputValue && b.Country !== inputValue){
return -1
}
if(a.Country !== inputValue && b.Country === inputValue){
return 1
}
return a.Country.localeCompare(b)
});
console.log(data)