본문 바로가기
기타/개인 공부

[JS/REACT] 리액트/바닐라JS 배열 내부 특정 객체 삭제 방법

by ㅇㅇ우너자나나 2022. 11. 24.

 

삭제

1. 불변성 유지 필요 없을 때

- for문과 splice(splice는 기존 배열의 값을 바꾼다) 를 이용한다.

const handleDelete = () => {
    const name = prompt("누구를 삭제하고 싶은가요?");
    updatedPerson((person) => {
      for (let i = 0; i < person.mentors.length; i++) {
        if (person.mentors[i].name === name) {
          person.mentors.splice(i, 1);
        }
      }
    });
  };

리액트에서 Immer 라이브러리를 사용할 때나 바닐라JS를 사용할 때는 불변성 유지를 꼭 지킬 필요 없다.

const handleDelete = () => {
	const name = prompt("누구를 삭제하고 싶은가요?");
	updatedPerson((person) => {
		const index = person.mentors.findIndex(m => m.name === name);
		person.mentors.splice(index, 1);
	});
};

findIndex를 통해 index를 찾고 splice 해도된다. 같은 방법

 

 

map을 통해 특정 조건을 만족하는 경우만 리턴하도록 하면, 조건을 만족하지 않는 경우에 반환이 안되는 것이 아니라 undefined가 리턴되기 때문에 내가 원하는 것이 아니었다.

 

2. 불변성 유지 필요할 때

리액트에서는 Immer같은 특수한 라이브러리를 사용하지 않는 한 상태값을 업데이트 하고싶을 때, 기존 값을 직접 수정하지 않고(불변성 유지),

새로운 데이터를 만들어서 상태를 업데이트 해줘야한다.

- filter를 사용한다.

  const handleDelete = () => {
    const name = prompt("누구를 삭제하고 싶은가요?");
    setPerson((person) => ({
      ...person,
      mentors: person.mentors.filter((mentor) => mentor.name !== name),
    }));
  };

 


 

번외) 추가하는 방법

- 불변성 유지하며 추가하는 방법

  const handleAdd = () => {
    const name = prompt("멘토의 이름은?");
    const title = prompt("멘토의 직함은?");
    setPerson((person) => ({
      ...person,
      mentors: [...person.mentors, { name, title }],
    }));
  };

 

이렇게 기존 객체를 바꾼 뒤, 기존 객체 자체를 스프레드 연산자를 통해 새로운 객체로 복사하는 방법도 있다. 

setPerson((person) => {
		person.mentors.push({
		name,
		title,
	});
	return { ...person };
});

 

- 불변성 유지 필요 없이 추가하는 방법

updatedPerson((person) => {
      person.mentors.push({
        name,
        title,
      });
    });

 


 

번외) 수정하는 방법

- 불변성 유지하며 수정하는 방법

const handleUpdate = () => {
    const prev = prompt(`누구의 이름을 바꾸고 싶은가요?`);
    const current = prompt(`이름을 무엇으로 바꾸고 싶은가요?`);
    setPerson((person) => ({
      ...person,
      mentors: person.mentors.map((mentor) => {
        if (mentor.name === prev) {
          return { ...mentor, name: current };
        }
        return mentor;
      }),
    }));
  };

- 불변성 유지 필요없이 수정하는 방법

updatedPerson((person) => {
      const mentor = person.mentors.find((m) => m.name === prev);
      mentor.name = current;
    });

 

'기타 > 개인 공부' 카테고리의 다른 글

nodejs console.log(req.body) undefined 가 나오는 경우  (0) 2022.11.20