영화 api 데이터에 있던 id 값을 통해 각 영화마다 리뷰를 작성할 수 있도록 구현했다.
그후 리뷰를 삭제할 수 있게 아래와 같이 코드를 작성했다.
function deleteComment(index) {
const comments = JSON.parse(localStorage.getItem("comments") || "[]");
const commentFilter = comments.filter(
(comment) => comment.movieId === searchParam("id")
);
const commentToDelete = commentFilter[index];
const inputPassword = prompt("비밀번호를 입력하세요.");
if (inputPassword === null) {
alert("취소되었습니다.");
return;
}
if (inputPassword === commentToDelete.password) {
const filteredComments = comments.filter(
(comment) => comment.time !== commentToDelete.time
);
localStorage.setItem("comments", JSON.stringify(filteredComments));
loadComments();
alert("댓글이 삭제되었습니다.");
} else {
alert("비밀번호가 일치하지 않습니다.");
}
}
filter()를 사용하여 삭제하려는 댓글을 제외한 나머지를 반환하고 다시 저장하여 로드 하는 형식이다.