选择对象数组中的特定字段返回未定义,但记录整个返回的整个数组给出ok值



我试图获得播客数据与' SpotifyAPI。我正在获取我的node.js服务器上的数据,并将其作为json发送到客户端。我收到一个类型化对象,并试图将这个对象推送到一个数组,因为我想有一个50个播客的数组,每个播客都是一个对象:

export interface Episode {
name: string;
description: string;
date: string;
img: string;
url: string
};

我正在发送token(到整个函数组件)和我想要获取的show的id

const fetchEpisodesData = async (ids: string[]) => {
let arr: any[] = [];
ids.forEach(async (id, index) => {
const response = await fetch(
`http://localhost:8080/podcastEpisodes?access_token=${tokenCode}&id=${id}`
)
const dataResponse = await response.json();
arr.push(dataResponse)
// )
});
console.log(arr);
};

当我console.log(arr)时,它显示了我想要的和一个对象数组,但当我console.log(arr[1])时,它返回未定义。什么好主意吗?下面是获取函数

的代码
export const useFetch = (tokenCode: string) => {
// console.log(tokenCode);
let array: any[] = [];
const [data, setData]: any = useState([]);
const [loading, setLoading] = useState(true);
const getData = async (id: string) => {
const response = await fetch(
`http://localhost:8080/podcastEpisodes?access_token=${tokenCode}&id=${id}`
);
const dataResponse = await response.json();
return dataResponse;
};
const fetchdata = async () => {
const response = await fetch(
`http://localhost:8080/podcast?access_token=${tokenCode}`
);
const dataResponse = await response.json();
// const item = dataResponse.results[0];
const myData = Object.keys(dataResponse).map((key) => {
return dataResponse[key];
});
// console.log(myData[0].show.id)
const idData = myData.map((data) => {
return data.show.id as string;
});
// console.log(idData, 'idData')
return idData;
// console.log(dataResponse);
};
const fetchEpisodesData = async (ids: string[]) => {
let arr: any[] = [];
ids.forEach(async (id, index) => {
const response = await fetch(
`http://localhost:8080/podcastEpisodes?access_token=${tokenCode}&id=${id}`
)
const dataResponse = await response.json();
arr.push(dataResponse)
// )
});
console.log(arr);
};
useEffect(() => {
fetchdata().then((res) => {
// console.log(res);
fetchEpisodesData(res);
});
}, [tokenCode]);
return { data, loading };
};

这里的问题有点微妙

你只推一个元素,dataResponse对象,到你的数组arr在这里:

arr.push(dataResponse)

由于您不推入任何其他值,并且Javascript中的数组是0索引的,因此您只能在arr[0]中找到您的值,但arr[1]将返回undefined

如果现在,如果您想用dataResponse中的数组填充数组arr,那么您应该在执行.push()扩展数组,因此您将推入dataResponse数组对象中找到的所有元素。

一样:

const dataResponse = await response.json();
// this works only **if** dataResponse is an array
// and you want to add all elements to your 'arr' array
arr.push(...dataResponse);