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

Vue中使用Axios获取JSON后,拆分日期与数值至对应数组

Vue中解析日期-数值JSON为两个独立数组

问题核心

你当前的代码仅将API响应的完整数据存入了totalVuePackages,但没有处理目标的日期-数值映射对象,也未将键值拆分到arrDate和arrValue数组中。另外需要注意:CoinDesk的该API返回数据里,日期与数值的映射是嵌套在bpi字段下的,不是直接在响应根节点。

解决方案代码

以下是两种可行的实现方式,均能准确拆分日期和数值到对应数组:

方式一:直接用Object.keys/Values提取

data: () => ({
  arrDate: [],
  arrValue: [],
  totalVuePackages: null
}),
created(){
  axios.get("https://api.coindesk.com/v1/bpi/historical/close.json?start=2019-01-01&end=2019-12-31")
    .then(response => {
      // 获取目标日期-数值映射对象
      const bpiData = response.data.bpi;
      // 提取所有日期字符串到arrDate
      this.arrDate = Object.keys(bpiData);
      // 提取所有数值到arrValue
      this.arrValue = Object.values(bpiData);
      // 可选:保存完整响应数据
      this.totalVuePackages = response.data;
    })
    .catch(error => {
      console.error('数据请求失败:', error);
    });
}

方式二:用Object.entries遍历(更直观)

data: () => ({
  arrDate: [],
  arrValue: [],
  totalVuePackages: null
}),
created(){
  axios.get("https://api.coindesk.com/v1/bpi/historical/close.json?start=2019-01-01&end=2019-12-31")
    .then(response => {
      const bpiData = response.data.bpi;
      // 先清空数组,避免重复数据
      this.arrDate = [];
      this.arrValue = [];
      // 遍历每个键值对,分别推入数组
      Object.entries(bpiData).forEach(([date, value]) => {
        this.arrDate.push(date);
        this.arrValue.push(value);
      });
      this.totalVuePackages = response.data;
    })
    .catch(error => {
      console.error('数据请求失败:', error);
    });
}

关键说明

  1. 正确获取目标数据:一定要访问response.data.bpi,API返回的完整结构包含bpi、disclaimer、time三个字段,只有bpi是你需要的日期-数值映射。
  2. 顺序一致性:现代浏览器中,Object.keys、Object.values、Object.entries都会按照对象属性的插入顺序返回结果,确保日期和数值一一对应。
  3. 错误处理:添加catch块可以在请求失败时输出错误信息,便于调试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 22:09:33