You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何遍历fetch返回的对象,提取指定格式的市场价格关联数据

实现方案

该接口返回的每个字段都以数字字符串为键存储对应行的数据,相同索引对应同一条数据,我们只要按索引遍历组装即可,具体实现如下:

完整JS代码

// 按要求指定字段顺序
const fieldOrder = ['Market_Name', 'District_Name', 'State', 'Commodity', 'Variety', 'datetimes', 'Price']

fetch('你的实际接口地址')
  .then(response => response.json())
  .then(rawData => {
    // 获取所有数据的索引列表
    const indexes = Object.keys(rawData.Market_Name)
    // 按索引遍历组装数据
    const formattedData = indexes.map(index => {
      const row = {}
      fieldOrder.forEach(field => {
        row[field] = rawData[field][index]
      })
      return row
    })
    // 此处formattedData就是符合要求的最终结果,可自行后续处理
    console.log(formattedData)
  })
  .catch(error => console.log('接口请求错误:', error))

可选调整

如果你只需要按顺序的字段值不需要键名,可将组装逻辑修改为返回数组:

const formattedData = indexes.map(index => fieldOrder.map(field => rawData[field][index]))

最终得到的就是二维数组,每条子数组内的值严格按照你要求的字段顺序排列。

内容的提问来源于stack exchange,提问作者Femi Oyedele

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 08:57:05