gpt4 book ai didi

javascript - 使用js对API调用响应进行排序

转载 作者:行者123 更新时间:2023-12-03 01:04:21 26 4
gpt4 key购买 nike

在我通过 API 调用请求一些数据后,我想对这些数据进行排序。该调用返回以下结构:

var values =[ 
{id: 1, type: "Gas", name: "G1,6", contractedPower: "2.5"},
{id: 2, type: "Gas", name: "G10", contractedPower: "2.5"},
{id: 3, type: "Gas", name: "G2,6", contractedPower: "2.5"},
{id: 4, type: "Gas", name: "G100", contractedPower: "2.5"},
{id: 5, type: "Electricity", name: "1X4A", contractedPower: "0.8"},
{id: 6, type: "Electricity", name: "1X6A", contractedPower: "0.8"},
{id: 7, type: "Electricity", name: "1X10A", contractedPower: "0.8"}, ....]

我尝试使用以下算法对其进行排序:

var PhysicalCapacities = [];
for (var i = 0; i < values.length; i++){
if (values[i].type == type){
PhysicalCapacities.push(values[i]);
}
}
var sortedArray = _(PhysicalCapacities).chain().sortBy(function(PhysicalCapacity) {
return PhysicalCapacity.name;}).value();

该算法首先过滤掉类型正确的。然后,它按名称值对其进行排序。唯一的问题是,它以半正确的顺序对它们进行排序:

对于天然气:

G1,6, G10, G100, G2,6


虽然应该是:

G1,6, G2,6, G10, G100


对于电力:

1x10A, 1X4A, 1X6A

虽然应该是:

1X4A, 1X6A, 1X10A

有谁知道如何调整它,以便它按照我想要的顺序返回?

最佳答案

你应该这样做:

  1. 替换键“name”的字母
  2. 将逗号替换为点
  3. 将数字转换为 float
  4. 对数组进行排序

像这样:

var PhysicalCapacities = [];
for (var i = 0; i < values.length; i++){
if (values[i].type == type){
PhysicalCapacities.push(values[i]);
}
}

var sortedArray = _(PhysicalCapacities).chain().sortBy(function(PhysicalCapacity) {
return parseFloat(PhysicalCapacity.name.replace(/[^0-9$.,]/g, '').replace(',','.'));
}).value();

关于javascript - 使用js对API调用响应进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52481583/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com