객체에서 첫번째 부분만 삭제하기

00_8_3·2021년 6월 13일
0

객체에서 특정 부분 삭제

아래와 같은 노래 큐가 있을 때

특정 가수의 부분만 재생해서 큐에서 삭제할려면 어떻게 해야하나?

const songRequestQueue = [
  {
    playList: {
      genre: "팝",
      title: "Sugar",
      singer: "마룬파이브",
    },
    customerName: "1번고객",
  },
  {
    playList: {
      genre: "팝",
      title: "Pysical",
      singer: "두아리파",
    },
    customerName: "2번고객",
  },
  {
    playList: {
      genre: "팝",
      title: "노스텔지아",
      singer: "두아리파",
    },
    customerName: "3번고객",
  },
];

이전

특정 가수 재생(특정 장르의 첫 부분만 삭제 시키기)

for loop로 songRequestQueue에서 가수와 같은 인덱스를 찾으면
해당 큐의 객체를 삭제하고 break로 빠져나와 첫번째만 삭제를 시킨다.

    if (singer && !genre && !type) {
      for (let i = 0; i < this.songRequestQueue.length; i++) {
        if (this.songRequestQueue[i].playList.singer === singer) {
          delete this.songRequestQueue[i];
          break;
        }
      }
    }

수정

특정 가수 재생(특정 장르의 첫 부분만 삭제 시키기)

findIndex로 첫 부분의 인덱스만 가져와 splice로 기존큐에서 제거하기

위와 다른점은 인덱스로 직접 접근을 통한 삭제

    if (singer && !genre && !type) {
      this.songRequestQueue.splice(
        this.songRequestQueue.findIndex(
          (req: SongRequest) => req.playList.singer === singer
        ),
        1
      );
    }

findIndex

findIndex() 메서드는 주어진 판별 함수를 만족하는 배열의 첫 번째 요소에 대한 인덱스를 반환합니다. 만족하는 요소가 없으면 -1을 반환합니다.
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex

0개의 댓글