2017-10-13 148 views
0

我無法理解最佳方法。如何通過嵌套獲取調用訪問嵌套數據?

我的目標是顯示嵌套的數據。

我用取這個網址 - https://horizons-json-cors.s3.amazonaws.com/products.json

這需要我到包含JSON的頁面。 JSON裏面有3個URL。每個網址都包含我需要的數據。

到目前爲止,我已經訪問了第一層,現在有一個項目網址的數組。我想我不明白在外部獲取調用中如何獲取數據。

這裏是我的代碼迄今(結果是網址,每個網址包含了我所需要的數據的數組。):

componentDidMount() { 
    console.log('Fetch'); 
    fetch("https://horizons-json-cors.s3.amazonaws.com/products.json") 
    .then((resp) => (resp.json())) 
    .then((json) => { 
     var productUrlArr = []; 
     for (var i = 0; i < json.length; i++) { 
     productUrlArr.push(json[i].url); 
     } 
    .catch((err) => { 
     console.log('error', err); 
    }); 
    }   

如果你們可以幫助我,真的穿行如何訪問下一個級別的數據,我真的很感激。

+0

你可以把下面的API調用的響應? –

+0

這是您擁有的API嗎?如果是這樣,我聽起來應該更改API,以便實際返回產品的數據而不是鏈接到另一個json文件。否則,這將是非常低效的,因爲您必須獲取第一個JSON文件,然後遍歷每個元素,然後對每個項目調用_additional_。 – dmon

+0

它不是我擁有的API。這是我學校的一個練習,它應該教會我們如何處理嵌套數據。我意識到這是低效的,但我仍然需要學習如何使用它。我的問題是弄清楚如何在外部獲取調用內迭代和調用每個項目/ url – aglaze

回答

0

你的代碼有點小錯誤。

它遺漏}).catch

有了它,你可以在陣列中使用您的數據。

componentDidMount(){ 
    console.log('Fetch'); 
    fetch("https://horizons-json-cors.s3.amazonaws.com/products.json") 
    .then((resp) => (resp.json())) 
    .then((json) => { 
     var productUrlArr = []; 
     for (var i = 0; i < json.length; i++) { 
     productUrlArr.push(json[i].url); 
     } 
     console.log(productUrlArr); 
    }).catch((err) => { 
     console.log('error', err); 
    }); 
} 

希望它有幫助。

0

很簡單。首先像你一樣首先獲得所有的網址。然後映射並傳入Promise.all

fetch("https://horizons-json-cors.s3.amazonaws.com/products.json") 
    .then((resp) => (resp.json())) 
    .then((json) => { 
    Promise.all(json.map(product => 
     fetch(product.url).then(resp => resp.text()) 
    )).then(texts => { 
     // catch all the data 
    }) 
    }).catch((err) => { 
    console.log('error', err); 
    }); 
2

您可以獲取數據內心的網址也這樣,

// 1. Outer Fetch call initiated here 
fetch("https://horizons-json-cors.s3.amazonaws.com/products.json") 
.then(res => { 
    return res.json() 
}) 
.then(res => { 

    // 2. array for storing url's retrieved from response 
    var urlArray = [] 

    if (res.length > 0) { 

     // 3. Push url inside urlArray 
     res.map(data => urlArray.push(data.url)) 
    } 

    // 4. an array of urls 
    return urlArray 
}) 
.then(urls => { 

    // Return an promise which will return "JSON response" array for all URLs. 
    // Promise.all means 「Wait for these things」 not 「Do these things」. 

    return Promise.all(urls.map(url => { 
     // Take url fetch response, return JSON response 
     return fetch(url).then(res => res.json()) 
    } 
    )) 
}) 
.then(res => { 
    // Store all objects into array for later use 
    var objArr = res; return objArr 
    }) 
//.then(...)