JS处理API返回的K线数组 数值乘213后保留原结构供图表使用
问题场景
- 开发类股票样式的柱状K线图,需要从API获取包含
open/close/high/low/volume字段的以太坊交易数据,已通过.map()方法提取对应字段。 - 需求:所有数值类字段结果需要乘以系数213后再传入图表展示,遍历数组时保持原有数据结构,可直接供图表调用。
- 原有可正常提取字段的代码如下:
const bars = response2.data.data.ethereum.dexTrades.map(el => ({ time: new Date(el.timeInterval.minute).getTime(), low: el.low, high: el.high, open: Number(el.open), close: Number(el.close), volume: el.volume }))
原有实现的问题
之前的实现逻辑是把low/high/open/close/volume拆分后单独做map遍历乘213,time字段单独提取不做乘法,最后再拼接为bars常量。虽然控制台打印单独处理后的字段数值正确,但最终输出的数据结构不符合图表要求,导致图表无法渲染。
错误实现代码如下:
// 拆分单独提取每个字段 const usdhigh = response2.data.data.ethereum.dexTrades.map(el => ({high: el.high})) const usdlow =response2.data.data.ethereum.dexTrades.map(el => ({low: el.low})) const usdopen = response2.data.data.ethereum.dexTrades.map(el => ({open: (el.open)})) const usdclose = response2.data.data.ethereum.dexTrades.map(el => ({close: (el.close)})) const usdvolume = response2.data.data.ethereum.dexTrades.map(el => ({volume: (el.volume)})) // 单独给每个字段数组的元素乘213 const usdhiughbnb = usdhigh.map((item) => { return { ...item, high: item.high * 213}; }); const usdlowbnb = usdlow.map((item) => { return { ...item, low: item.low * 213}; }); const usdopenbnb = usdopen.map((item) => { return { ...item, open: item.open * 213}; }); const usdclosebnb = usdclose.map((item) => { return { ...item, close: item.close * 213}; }); const usdvolumebnb = usdvolume.map((item) => { return { ...item, volume: item.volume * 213}; }); // 单独提取时间字段 let timesf = response2.data.data.ethereum.dexTrades.map(el => ({ time: new Date(el.timeInterval.minute).getTime() })) // 错误的拼接方式,最终结构完全不符合要求 const bars = ( time = timesf, low = usdlowbnb, high = usdhiughbnb, open = Number(usdopenbnb), close = Number(usdclosebnb), volume = usdvolumebnb )
错误原因:拆分多个map遍历后,每个字段都是独立的对象数组,最后拼接时直接把数组赋值给单条数据的属性,最终输出数组嵌套数组的错误结构,和图表要求的「数组内每个元素为包含time/low/high/open/close/volume属性的单个对象」结构完全不匹配。
正确实现方案
不需要拆分字段多次遍历,直接在原有.map()生成bars的逻辑里,对需要乘系数的数值字段直接做乘法即可,time字段保持原有逻辑不变,输出结构和原代码完全一致,可直接传入图表使用。
实现代码:
const bars = response2.data.data.ethereum.dexTrades.map(el => ({ time: new Date(el.timeInterval.minute).getTime(), // 时间字段不做计算,保持原逻辑 low: el.low * 213, high: el.high * 213, open: Number(el.open) * 213, close: Number(el.close) * 213, volume: el.volume * 213 }))
- 该实现只做一次数组遍历,性能比多次拆分遍历更高
- 输出数据结构和原有可正常提取字段的代码完全一致,不需要修改图表侧的接收逻辑
- 所有数值字段都已乘以213,满足展示需求
内容的提问来源于stack exchange,提问作者Ali
相关产品推荐
相关产品推荐

