You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

对API返回JSON按日期排序时报Uncaught (inPromise) sort is not a function错误

报错原因
  • sort是数组实例的专属方法,你当前调用sort的变量是字符串类型,自然不存在这个方法:你代码中使用JSON.stringify(response.body)将原本的JS数组/对象转成了JSON格式字符串,直接对字符串执行排序操作必然触发类型错误。
  • 你已经通过response.json()完成了接口返回数据的解析,不需要额外做序列化处理,除非你的Lambda接口特殊配置了将body内容转为JSON字符串返回。
修复代码

根据你的接口返回格式二选一即可:

常规场景:response.body直接就是待排序的数组

直接去掉JSON.stringify步骤,对原始数组执行排序即可:

async function callAwsLambdaFunction() {
  fetch( 'URL',  {
    method: 'GET'
  })
  .then(response => response.json())
  .then((response) => {
    // 直接取接口返回的数组,浅拷贝一份避免修改原响应数据
    const dataArr = [...response.body];
    // 对数组执行排序
    dataArr.sort(function(a, b) {
      const dateA = new Date(a.in_time), dateB = new Date(b.in_time);
      return dateA - dateB;
    });
    console.log(dataArr);
    // 如果要在页面展示格式化后的JSON,可以序列化后输出
    document.getElementById("myDiv").innerHTML = JSON.stringify(dataArr, null, 2);
  });
}

特殊场景:response.body是JSON格式字符串(Lambda网关常见配置)

先将字符串反序列化为数组再排序:

async function callAwsLambdaFunction() {
  fetch( 'URL',  {
    method: 'GET'
  })
  .then(response => response.json())
  .then((response) => {
    // 先把JSON字符串转成JS数组
    const dataArr = JSON.parse(response.body);
    // 对数组执行排序
    dataArr.sort(function(a, b) {
      const dateA = new Date(a.in_time), dateB = new Date(b.in_time);
      return dateA - dateB;
    });
    console.log(dataArr);
    document.getElementById("myDiv").innerHTML = JSON.stringify(dataArr, null, 2);
  });
}
额外说明

如果你要排序的源数据是对象而不是数组,需要先取出对象中待排序的数组属性,再执行排序操作。如果需要对对象的键值对排序,Object.entries(待排序对象)会返回二维数组,对这个返回结果调用sort方法即可。

内容的提问来源于stack exchange,提问作者Aldiyar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 08:06:03