【问题标题】:Sort API Response without Storing the Data using JavaScript在不使用 JavaScript 存储数据的情况下对 API 响应进行排序
【发布时间】:2020-09-13 02:20:33
【问题描述】:

我正在使用下面的代码调用 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 Endpoint 并进行排序,而不将响应存储在 CODE 中。

错误:

> error: Uncaught ReferenceError: ListModels is not defined

【问题讨论】:

    标签: javascript json reactjs api sorting


    【解决方案1】:

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

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

    【讨论】:

    • 我遇到了同样的错误,>>> UnhandledPromiseRejectionWarning: ReferenceError: ListModels is not defined 请帮忙
    • ListModels 似乎未定义,因为您的(上部)脚本中没有提及,并且 API 响应(下部 sn-p)不是有效的 JSON。那么,为什么要使用这个 ListModels?
    猜你喜欢
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多