首页 > 解决方案 > Vue Axios API 对象到对象数组

问题描述

我目前在我的网站上显示货币数据时遇到问题,我想在其中显示货币的简称以及货币的价值。

我正在使用这个 api,以美元为基础:https ://api.exchangeratesapi.io/latest?base=USD

我运行并获取数据的代码是:

getCurrencies() {
  axios
    .get("https://api.exchangeratesapi.io/latest?base=USD")
    .then(response => {
      this.currencies = response.data.rates;
      console.log(this.currencies);
    });
}

我得到的输出当然只是货币的价值,我正在寻找一种将这些对象分解为对象数组的方法,我可以在其中调用 ex:currency.short 和 currency.price

这样,我将在网站上分别显示短名称和价格,而不是在使用“response.data.rates”时仅显示货币价值

标签: apivue.jsaxioscurrency

解决方案


您可以使用该Object.keys方法迭代速率和map函数来创建您的对象,就像这样:

this.currencies = Object.keys(response.data.rates).map(k => ({
    short: k,
    price: response.data.rates[k]
}))

推荐阅读