【发布时间】:2021-01-19 01:36:18
【问题描述】:
我正在使用 Axios 执行对公共 API 的 GET 请求,如果名称相同,我需要组合名称并将值添加到仅显示前 20 个(这是一个大数据集)基于最高最低金额(升序)。
Axios 响应
[
{
name: "foo1",
value: "8123.30"
},
{
name: "foo1",
value: "2852.13"
},
{
name: "foo2",
value: "5132.23"
},
{
name: "foo1",
value: "1224.20"
},
{
name: "foo2",
value: "1285.23"
}
1200...
];
预期输出
[
{ name: "foo1",
value: "12199.63" // from all combined "foo1" amounts in the dataset
},
{
name: "foo2",
value: "6417.46" // from all combined "foo2" amounts in the dataset
},
18..
]
我试图做这样的事情......
const fetchData = () => {
return axios.get(url)
.then((response) => response.data)
};
function onlyWhatINeed() {
const newArr = []
return fetchData().then(data => {
const sortedData = data.sort((a, b) => parseFloat(a.value) - parseFloat(b.value));
// I need to loop through the dataset and add all the "values" up
// returning only the top 20 highest values in an array of those objects
newArr.push(sortedData)
})
}
但我很困惑如何将这些数据推送到排序数据的新数组(按升序排列的前 20 个值)并在我的 Web 应用程序中使用这些数据。我对创建 REST API 有点陌生,所以如果您能提供文章和/或资源,以便我能多了解一点,那将是一个很棒的奖励!
【问题讨论】:
-
这个数据集有多大(有多少条目)?
-
axios 返回 1220 个对象
标签: javascript node.js sorting data-structures axios