[TIL] map 함수를 사용하고 싶지만 조건이 다를 때,

Eden·2022년 9월 4일
0

TIL

목록 보기
12/23
post-thumbnail

.map()을 이용해 반복시키고 싶은 무언가가 있다.

[
    { id: 0, title: '모집 구분', content: '스터디' },
    { id: 1, title: '진행 방식', content: '온라인' },
    { id: 2, title: '모집 인원', content: '인원 미정' },
    { id: 3, title: '시작 예정', content: '2022.10.29' },
    { id: 4, title: '연락 방법', content: 'justcode6@justcode.com' },
    { id: 5, title: '예상 기간', content: '1개월' },
    {
      id: 6,
      title: '사용 언어',
      imgSrc: [
        '/images/javascript.png',
        '/images/react.png',
        '/images/nodejs.png',
        '/images/express.png',
        '/images/mysql.png',
      ],
    },
  ]

그런데 id 0~5까지의 키는 동일하지만 id 6번의 key는 어딘가 다르다.

그럴 때 switch문을 이용해 map함수를 적절하게 사용할 수 있다.

<script>
{infoArray.map((item) => {
	//switch의 조건식에 원하는 조건을 써주고
    switch (item.id) {
      //그 조건에 부합하는 값을 찾았을 경우에
      case 6: {
 /*item.imgSrc === undefined || item.imgSrc === null ? [] : item.imgSrc 와 같은 의미
 item.imgSrc ?? [] 는 그 값이 undefined이나 null이면 빈 배열을 반환하고, 그게 아니면 원래 값을 반환하라는 조건을 준 값이다*/
        const list = item.imgSrc ?? [];
        //이 값을 리턴해 주기로 한다.
        return (
          <li key={item.id}>
            <p>{item.title}</p>
            <div>
              {list.map((img) => (
                <img key={img} alt={img} src={img} width={"30px"} />
              ))}
            </div>
          </li>
        );
      }
      //그리고 그 조건이 아니라면,
      default: {
      	//이렇게 리턴해주기로 한다.
        return (
          <li key={item.id}>
            <p>{item.title}</p>
            <p>{item.content}</p>
          </li>
        );
      }
    }
  });
}

</script>
profile
one part.

0개의 댓글