【发布时间】:2021-07-24 02:46:37
【问题描述】:
我从我的 API 端点返回一个非常大的对象。 它是一个具有多个数组的对象。在它们中的每一个中作为 url(例如 item.[0].images[0].url)。我想创建一个新数组,只使用 url 并将它们存储在我的 Redux 存储中。
我尝试使用过滤方法,但每次都返回相同的大数组,没有任何更改。
此外,我注意到如果我 console.log(typeof res.data.items) 我得到一个对象而不是一个数组作为输出。我很困惑,因为我的控制台也说 res.data.items 是一个数组。
这是我的 res 对象的一部分
{data: {…}, status: 200, statusText: "", headers: {…}, config: {…}, …}
config: {url: "/me/top/artists?limit=20&offset=11", method: "get", headers: {…}, baseURL: "https://api.spotify.com/v1", transformRequest: Array(1), …}
data:
href: "https://api.spotify.com/v1/me/top/artists?limit=20&offset=11"
items: Array(20)
0:
external_urls: {spotify: "https://open.spotify.com/artist/0fA0VVWsXO9YnASrzqfmYu"}
followers: {href: null, total: 4774667}
genres: (3) ["hip hop", "ohio hip hop", "rap"]
href: "https://api.spotify.com/v1/artists/0fA0VVWsXO9YnASrzqfmYu"
id: "0fA0VVWsXO9YnASrzqfmYu"
images: Array(3)
0:
height: 640
url: "https://i.scdn.co/image/4cb57ae1ef87546455db9cf65ba414c311ff459a"
1: {…}
2: {…}
....
这是我的职责
.then((res) => {
***let newdata = res.data.items.filter((url) => url.images[0].url)*** // not working
console.log('newdata', newdata) // getting back res.data.items
console.log(res.data.items) // Array
console.log('res', res)
console.log(typeof res.data.items) // Object ?
dispatch({
type: FETCH_TOP_25_ALBUMS,
payload: newdata,
})
})
【问题讨论】:
-
您需要使用 map 而不是 filter 以防您想要转换数组。尝试改用 res.data.items.map
标签: javascript arrays reactjs object filter