댓글 수정 및 삭제

개발공부·2023년 1월 29일
0
post-thumbnail

* 결과

1) 댓글 생성 후 수정

2) 댓글 삭제

* 참고

객체 설명 - 간단한 버전

객체 업데이트 2

const arrayList = [{Comments: {id: 'a'}, id:1}, {Comments: {id: 'b'}, id:2}, {Comments: {id: 'c'}, id:3}]
const findIdx = arrayList.map(object => object.Comments.id).indexOf('a');
console.log(findIdx); //0

* 문제점

1) 댓글 삭제

▶ 특정 id 값을 찾아 삭제하는 것이 핵심

* 넣고자 하는 위치

const project = [
{Comments: [{id: 45, content: "댓글 뭐시기45"}, {id: 44, content: "댓글 뭐시기44"}], id: 58},
{Comments: [{id: 35, content: "댓글 뭐시기35"}, {id: 34, content: "댓글 뭐시기34"}], id: 48}
]

* 삭제하고자 하는 데이터

const data = {id: 44}

* 원하는 상태

▶ id가 44인 댓글을 삭제하길 원함

* 함수

const filteredData = (list) => {
        list.forEach((post) => {
          post.Comments = post.Comments.filter(
            (comment) => ![data.id].includes(comment.id)
          );
        });
        return list;
      };
filteredData(project);

2) 댓글 수정

▶ 배열 안에 여러 객체들 중 특정 id를 찾아 수정하는 것이 핵심

* 넣고자 하는 위치

const project = [
{Comments: [{id: 45, content: "댓글 뭐시기45"}, {id: 44, content: "댓글 뭐시기44"}], id: 58},
{Comments: [{id: 35, content: "댓글 뭐시기35"}, {id: 34, content: "댓글 뭐시기34"}], id: 48}
]

* 변경하기를 원하는 데이터

const data = {id: 45, content: '댓글댓글127979qjkejqlkwjekqjjqweowpqwokroqwpkeoqwkpwokrqkqkoqowllsll123123k 2ok3o1k23pdqwweeqww', PostId: 58}

* 원하는 상태

▶ id가 45인 content인 "댓글 뭐시기45"를 "댓글댓글127979qjkejqlkwjekqjjqweowpqwokroqwpkeoqwkpwokrqkqkoqowllsll123123k 2ok3o1k23pdqwweeqww"로 변경하는 것

* 함수

 const reviseData = (list) => {
        list.forEach((post) => {
          post.Comments.map((comment) => {
            if (comment.id === data.id) {
              comment.content = data.content;
            }
          });
        });
        return list;
      };

reviseData(project)
profile
개발 블로그, 티스토리(https://ba-gotocode131.tistory.com/)로 갈아탐

0개의 댓글