您将如何遍历所有0, 1, 2
属性并检索值
不仅可以通过myArray[0].postId
或myArray[1].postId
来完成。这是手动执行的操作。
这是一种循环访问[]
数字myArray[0].postId
,myArray[1].postId
等的方法。
例如遍历这些项目
这是例子
export const GetPosts = () => {
return (dispatch, getState) => {
return Axios.get('/api/posts/myPosts')
.then( (res) => {
const data = res.data
const likes = res.data // gets the first item within array, and shows likes.
const myLikes = likes.map( (post,i) => {
return post.Likes
},[])
const myLikes2 = myLikes.map( (like,i) => {
return like
})
const myLikes3 = myLikes2.flat();
const myLikes4 = myLikes3.reduce( (acc,post) => {
return acc.concat(post)
},[])
console.log(myLikes4) // trying to get all like postIds not just [0]
dispatch({type: GET_POSTS, data, myLikes})
})
}
}
答案 0 :(得分:0)
也许像这样将帖子Ids作为数组保留下来,以保持脚本风格:
git
这会将myEntry.postId添加到myArray中每个条目的myPostIds数组中。
答案 1 :(得分:0)
很多好的解决方案,不妨使用@ d-h-e注释示例,谢谢大家的帮助。
export const GetPosts = () => {
return (dispatch, getState) => {
return Axios.get('/api/posts/myPosts')
.then( (res) => {
const data = res.data
const likes = res.data // gets the first item within array, and shows likes.
const myLikes = likes.map( (post,i) => {
return post.Likes
},[])
const myLikes2 = myLikes.map( (like,i) => {
return like
})
const myLikes3 = myLikes2.flat();
const myLikes4 = myLikes3.reduce( (acc,post) => {
return acc.concat(post)
},[])
myLikes4.forEach(el => console.log(el.postId));
dispatch({type: GET_POSTS, data, myLikes})
})
}
}