下面的代码片段是我的脚本,用于存储在单个Array(const存储)中的所有数据,我需要以结构化的方式利用这些数据。为了之后“简单”地使用它们。
console.log(store)
在控制台中显示所需的数据结构:
(2) [{…}, {…}]
0: {ID: "freecodecamp", streams: {…}, users: {…}, channels: {…}}
1: {ID: "funfunfunction", channels: {…}, users: {…}, streams: {…}}
console.log(store[0].ID)
显示所需的结果:"freecodecamp"
但store[0].users
,store[0].channels
和store[0].streams
输出undefined
。
我不明白为什么。虽然一切都适用于store[0].ID
const matchCharUrl = str => str.match(/[^/]/g).join('')
// Twitch.tv API call and settings
// --------------------------------------------------
const twitchAPI = () => {
// const baseUrl = 'https://api.twitch.tv/kraken' // Twitch API base URL
const baseUrl = 'https://wind-bow.glitch.me/twitch-api/' // FCC Twitch API Pass-through
const params = ['users/', 'channels/', 'streams/'] // Twitch API, enabled root
// suffix (channel or user) identifier
const identifiers = ['freecodecamp', 'funfunfunction']
// array with datas that will be exploit in a function ( displayResults() )
const store = []
identifiers.forEach((ID, index) => {
const obj = {ID}
for(const param of params){
const urlAPI = baseUrl + param + ID
fetch(urlAPI, {
method: 'GET'
}).then(res => {
if(res.ok) return res.json()
throw new Error('Network response error. Status Code:', res.status, res.statusText)
}).then(data => {
// Data structure of var store:
// store = [ {id: freecodecamp, channels: {data}, streams: {data}, users: {data} } ]
obj[matchCharUrl(param)] = data
}).catch(err => {
console.log('Fetch Error:', err)
})
}
store.push(obj)
})
console.log(store) // OK
console.log(store[0]) // OK
console.log(store[0].ID) // OK
console.log(store[0].users) // undefined
console.log(store[0].channels) // undefined
console.log(store[0].streams) // undefined
// displayResults(store)
}
twitchAPI()