如果返回的元素为null,如何回溯数组的索引



我正在处理一个问题,即通过API调用返回的数组进行映射,以创建图点对象的数组,但返回的数据不可靠且包含空值。为了简化这个问题,下面是我现在所拥有的一个简短版本:

const APITimestamps = ['123','124','125','126','127','128']
const APIPrices = ['22.34','22,45',NULL,NULL,'22.89','22.32']
const chartData = APITimestamps.map((timestamp, index) => {
let graphPoint = {}
graphPoint.timestamp = APITimestamps[index]
graphPoint.price = APIPrices[index]
return graphPoint
}

映射按原样工作,但是我需要将chartData中的空值去掉,因为API没有一些时间戳的价格。我想做的是回溯正在映射的APIPrices的索引,直到找到一个非null值,在上面的情况下,它将是['22.34','22,45','22.45','22.89','22.32']。有什么关于如何实现这一点的指针吗?

您可以使用for循环,该循环从当前索引向后迭代并查找第一个非null值。

const APITimestamps = ['123','124','125','126','127','128']
const APIPrices = ['22.34','22,45',null,null,'22.89','22.32']
const chartData = APITimestamps.map((timestamp, index) => {
let graphPoint = {}
graphPoint.timestamp = APITimestamps[index]
for(let i = index; i >= 0; i--){
if(APIPrices[i] !== null){
graphPoint.price = APIPrices[i];
break;
}
}
return graphPoint
});
console.log(chartData);

最新更新