javascript - 在不使用 JavaScript 存储数据的情况下对 API 响应进行排序
问题描述
我正在使用下面的代码调用 GET API,然后使用其中列出的对象之一对响应进行排序。有人告诉我先将响应转换为数组,然后应用排序功能,但这似乎很困难,而且我错过了一些东西来对生成的数组进行排序。请帮助我,已经尝试了很多天。
我的代码:
url2 = "https://SampleAPI";
function fetchdata(){
fetch(url2)
.then(response=>{
return response.json();
})
.then(data=> {
console.log(data.data) // Getting the "Unsroted Response" Here
})
};
fetchdata(); //
const sortedResponse = ListModels.sort(function(a, b) { return parseInt(a.associateId) - parseInt(b.associateId) });
console.log("SORTED: ", sortedResponse) // Using to SORT THE RESPONSE WITH "associateId"
以上 JS 代码的 API 响应:
{
ListModels:(4) [
{
searchRank:0,
firstName:"Micheal",
lastName:"Brook",
associateId:"40",
payRateType:"Cost-only",
doctorStatus:null,
contractStartDate:"0001-01-01T00:00:00"
},
{
searchRank:0,
firstName:"Travis",
lastName:"Mayn",
associateId:"20",
payRateType:"Samp-only",
doctorStatus:null,
contractStartDate:"0001-01-01T00:00:00"
},
{
searchRank:0,
firstName:"Berry",
lastName:"Brooks",
associateId:"43",
payRateType:"Samp-only",
doctorStatus:null,
contractStartDate:"0001-01-01T00:00:00"
},
{
searchRank:0,
firstName:"Kim",
lastName:"Reed",
associateId:"25",
payRateType:"Samp-only",
doctorStatus:null,
contractStartDate:"0001-01-01T00:00:00"
}
],
totalRecord:4
}
我想使用“associateId”对 API 响应进行排序,但是使用我的排序行,我得到了错误。请帮助我,我被告知要点击 API 端点并进行排序,而不会将响应存储在 CODE 中。
错误:
> error: Uncaught ReferenceError: ListModels is not defined
解决方案
您必须在响应处理程序中移动排序:
url2 = "https://SampleAPI";
function fetchdata(){
fetch(url2)
.then(response=>{
return response.json();
})
.then(data=> {
console.log(data.data) // Getting the "Unsroted Response" Here
const list = data.data;
const sortedResponse = list.sort(function(a, b) { return parseInt(a.associateId) - parseInt(b.associateId) });
console.log("SORTED: ", sortedResponse) // Using to SORT THE RESPONSE WITH "associateId" })
};
fetchdata(); //
紧随其后的操作fetchdata
在响应来自服务器之前执行。
推荐阅读
- python - Azure 服务器未能对请求进行身份验证
- python - 打包一个二级子目录
- firebase - Flutter Firebase Cloud Messaging - 应用程序在后台时的通知
- php - Woocommerce 重复产品然后增加最高 SKU
- angular - 了解 ngOnInit
- mysql - 从左连接中删除多个重复记录
- reactjs - 为什么反应时刻增加一小时?
- angular - 当 InjectionToken 被用作依赖项时,Ionic 'build –prod' 失败
- c# - GameCard 值识别使用 AForge.NET 给出错误结果
- php - 注意:未定义索引:第 28 行 C:\xampp\htdocs\8990API\login.php 中的用户名