如何遍历Alphavantage API返回的二元对象嵌套数组提取股票数据
实现代码与说明
你现有代码存在两个可优化点:
- 数组的
filter、map均为同步方法,前面不需要加await - 过滤完无效数据后没有做目标字段提取,也没有将处理后的数据存入组件状态,无法直接驱动UI渲染
核心数据处理逻辑
过滤完长度为1的无效子数组后,直接遍历剩余有效项,从每个子数组的元信息对象中提取股票代码,从行情对象中提取收盘价,组装成仅含所需字段的结构化数组即可:
import { useEffect, useState } from 'react'; import { useDispatch } from 'react-redux'; // 替换为你实际的Redux slice路径 import { getStocks } from '@/store/stockSlice'; const StockList = ({ tickerArray, type }) => { // 存储处理完成、可直接渲染的股票数据 const [stockList, setStockList] = useState([]); const dispatch = useDispatch(); useEffect(() => { const fetchStocks = async () => { try { const response = await dispatch(getStocks({ tickerArray, type })).unwrap(); const rawData = response.data; const formattedData = rawData // 过滤长度为1的无效子数组 .filter(each => each.length !== 1) // 遍历提取需要的字段 .map(item => { // 每个有效子数组固定为[元信息对象, 行情对象],直接解构取值 const [meta, quote] = item; return { symbol: meta["2. Symbol"], // 字符串转数字,按需保留2位小数 closingPrice: Number(quote["4. close"]).toFixed(2) } }); setStockList(formattedData); } catch (error) { console.log('股票数据请求失败:', error); } } fetchStocks(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [tickerArray, type])
表格渲染代码
处理完成的数据直接遍历渲染表格行即可:
return ( <div className="s-table-container"> <table className="s-table"> <thead> <tr> <th>Stock Symbol</th> <th>closing price</th> </tr> </thead> <tbody> {stockList.map(stock => ( <tr key={stock.symbol}> <td>{stock.symbol}</td> <td>{stock.closingPrice}</td> </tr> ))} </tbody> </table> </div> ) } export default StockList;
兼容提示:如果接口返回的子数组内对象顺序不固定,可以通过判断对象是否存在
"2. Symbol"字段区分元信息和行情数据,避免硬编码下标导致的取值错位。
内容的提问来源于stack exchange,提问作者Ifeanyi Chima
相关产品推荐
相关产品推荐

