Programming/JavaScript
[JavaScript] map(), filter() 같이 사용하기
aldrn29
2022. 8. 21. 20:41
게시물을 출력하는 과정에서 불필요한 게시물은 제외해야했다. 내 경우에는 같은 유저의 게시물을 보여주면 안됐기 때문에, filter로 한번 걸러주고 나머지를 map으로 돌려서 뿌려주었다. 전체 코드를 살펴보자.
전체 코드
const Posts = () => {
const [otherPosts, setOtherPosts] = useState([])
const getOtherPosts = async (producId) => {
const res = await get(...);
setOtherPosts(res.data.data...);
};
useEffect(() => {
getOtherPosts();
}, []);
return (
<div>
{otherPosts.filter((post) => userId !== post.user_id)
.map((post, index) => (
<Card key={index} />
))
}
</div>
)
}
728x90
728x90