0

How to extract multiple objects from an array of objects, in this case dollars and euros, if I get data from an API in mounted using axios? I need to display the current exchange rate of USD and EUR

<script>
import axios from 'axios';

export default {
  name: 'Header',
  components: {

  },
  data() {
    return {
      currency: null,
      newCurrency: null,
    };
  },
  mounted() {
    axios
      .get('https://bank.gov.ua/NBUStatService/v1/statdirectory/exchange?json')
      .then(response => (this.currency = response.data))
      .catch((error) => console.log(error.message));
  },
}
</script>

data received from API

  • use v-if in template when you loop over – Dave Sep 15 '22 at 16:39
  • Hello @Vlad. You've got an array of currencies. So within that array you need to `filter` exchange rate of `USD` and exchange rate of `EUR`. Those are two `filter` operations on an array. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter thus `const eurExchangeRate = this.currencies.filter(currency => currency.cc === 'EUR')[0].rate` and usdExchangeRate = this.currencies.filter(currency => currency.cc === 'USD')[0].rate` – maljukan Sep 15 '22 at 16:40
  • Thank you very much for your answer, so I have to filter the array in the methods? Because when I do this I get the error "Cannot read properties of null (reading 'forEach')" – Vlad Poligas Sep 15 '22 at 16:43
  • @maljukan Thank you so much you are incredible! – Vlad Poligas Sep 15 '22 at 16:45

1 Answers1

1

This is the duplicate question of the more general one Get JavaScript object from array of objects by value of property

kissu
  • 40,416
  • 14
  • 65
  • 133
maljukan
  • 2,148
  • 2
  • 25
  • 35