首页 > 解决方案 > 在不使用 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

标签: javascriptjsonreactjsapisorting

解决方案


您必须在响应处理程序中移动排序:

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在响应来自服务器之前执行。


推荐阅读