Reputation: 81
I am new to Vue.js and been a while since I didn't use javascript, my knowledge is limited and my question may seem stupid.
I have been following this tutorial which was a bit out of date before Currency Convert API have changed their JSON responses (if that we call them).
So I used axios to get the API and this code below works perfectly
const key = this.from+'_'+this.to;
const apiConv = axios.get('https://free.currencyconverterapi.com/api/v6/convert?q='+key+'&compact=ultra&apiKey=API_KEY///');
apiConv.then(response =>{
console.log(response);
this.result = response.data[key];
My question here is as the following:
if const key = this.from+'_'+this.to;
= USD_EUR means this.result = response.data.key;
must work! But I get undefined
, when I try this.result = response.data.USD_EUR;
works with no problems and I get my value while key = USD_EUR
This is the data I get from console.log(response);
{data: {…}, status: 200, statusText: "", headers: {…}, config: {…}, …}config: {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …}data: USD_EUR: 0.87961__proto__: Objectheaders: {content-type: "application/json; charset=utf-8"}request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}status: 200statusText: ""__proto__: Object
Can anyone please explain to me why I have to add data[key]
to get the value and data.key
doesn't work
Upvotes: 0
Views: 181
Reputation: 658
When you try to use data.key
, you are asking JavaScript to get an item named key
(not USD_EUR
) from the data
object. Since your data
does not contain a value against key
(literally key
, not the value of key
), it will give you undefined
.
When you use data[key]
, then you are asking JavaScript to get the value of an item represented by the key
variable. In this case, JavaScript will figure out that key
has the value USD_EUR
and try to get data.USD_EUR
and you will get your value.
Remember - the dot notation is for when the child key is not dynamic. You cannot use the dot notation to get values from keys whose names are dynamic. In such cases, you always need to use the array accessing pattern (using object.[key]
).
Upvotes: 1