筆記一下在學習撰寫 JavaScript 的 Async (非同步) 特性和引入API時,所遇上的物件中的物件(A object in the object)的取值問題。
重點整理
Async 非同步處理
這個是 JavaScript 的特性。若使用 AXIOS 的方式向 API 索取資料的話,其獲得的資料儲存後,要立刻在其後呼叫對應要使用的函式。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | //相關的啟用 function 要放在 axios 裡,以免async特性導致資料抓不到 let data = {}    axios      .get('https://api.exchangerate-api.com/v4/latest/USD')     .then((response) => {       data = Object.entries(response.data.rates)       round(data)       reverse(data)       display(data)       console.log(data) // 輸出為response.data.rates 的值     })     .catch((error) => console.log(error)) console.log(data) // 輸出為空集合 | 
JSON Object in a object
API: https://api.exchangerate-api.com/v4/latest/USD
Object 中有 Object 的情況。因為 Object 和 Array 為不同的結構,無法像 array 用 “array[0]” 的方式來取值。此時,可以運用 Object.entries (MDN Resource) 來解決。所獲得值為 [key, value] 形式。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | //相關的啟用 function 要放在 axios 裡,以免async特性導致資料抓不到  axios      .get('https://api.exchangerate-api.com/v4/latest/USD')     .then((response) => {       console.log(response.data.rates)        /* 此時為 {       "base": "USD",       "date": "2019-05-12",       "time_last_updated": 1557619202,       "rates": {       "USD": 1,       "AUD": 1.430288,       "BRL": 3.953831}        }*/       data = Object.entries(response.data.rates)       console.log(data)       /*       Array(34)          0: (2) ["TWD", "1.000"]          1: (2)["AUD", "0.046"]       */       })     .catch((error) => console.log(error)) | 





