如何对接口返回的res.data按_id字段进行排序?
按_id字段排序res.data的解决方案
你可以利用JavaScript的Array.sort()方法对返回的res.data按_id字段进行排序,注意先复制原数组避免直接修改源数据,再执行排序操作:
修改后的代码
const [income, setIncome] = useState([]); const [perc, setPerc] = useState(0); useEffect(() => { const getIncome = async () => { try { const res = await userRequest.get("orders/income"); // 按_id升序排序(需降序则改为b._id - a._id) const sortedData = [...res.data].sort((a, b) => a._id - b._id); setIncome(sortedData); // 基于排序后的数组计算perc setPerc((sortedData[1].total * 100) / sortedData[0].total - 100); console.log(sortedData); } catch {} }; getIncome(); }, []);
关键说明
[...res.data]:通过扩展运算符复制原数组,避免直接修改res.data的原始引用.sort((a, b) => a._id - b._id):通过比较_id的数值差实现升序排序;切换为b._id - a._id即可得到降序结果- 计算
perc时使用排序后的sortedData,确保基于有序数组完成计算
排序后你的数组会呈现如下有序状态:
0: {_id: 6, total: 448} 1: {_id: 7, total: 900} 2: {_id: 8, total: 100} 3: {_id: 9, total: 700} 4: {_id: 10, total: 990} 5: {_id: 11, total: 20}
内容的提问来源于stack exchange,提问作者Darkpsinight
相关产品推荐
相关产品推荐

