Object

YJ·2023년 1월 14일
0

아래 설명을 읽고 getExamResult 함수를 구현하세요.
scores ::
인자 scores 는 다음과 같은 객체입니다. 객체의 요소의 갯수 및 키의 이름들은 달라질 수 있습니다. 객체의 값은 다음 9가지 알파벳 성적을 의미하는 문자열 중에서 하나를 가지고 있습니다.
'A+', 'A', 'B+', 'B', 'C+', 'C', 'D+', 'D', 'F'
< scores 인자 예시 >
{
'생활속의회계': 'C',
'논리적글쓰기': 'B',
'독일문화의이해': 'B+',
'기초수학': 'D+',
'영어회화': 'C+',
'인지발달심리학': 'A+',
}
requiredClasses ::
인자 requiredClasses는 다음과 같이 과목명이 문자열로 된 배열입니다.
< requiredClasses 인자 예시 >
['영어회화', '기초수학', '공학수학', '컴퓨터과학개론']
다음 조건을 만족하는 객체를 반환하도록 함수를 구현해주세요.
scores 객체가 가지고 있는 키들은 새로운 객체에 포함되어야 합니다. 단, 그 값들은 다음 원리에 따라 숫자로 바뀌어 할당되어야 합니다. (알파벳 성적 => 숫자 성적)
A+ => 4.5
A => 4
B+ => 3.5
B => 3
C+ => 2.5
C => 2
D+ => 1.5
D => 1
F => 0
requiredClasses 배열의 요소로는 존재하지만, scores의 키로는 존재하지 않는 항목이 있다면, 해당 요소는 새로운 객체의 키가 되고, 값으로 0을 가져야 합니다.

우선 알파벳 성적이 숫자 성적으로 바뀌는 과정을 적어보자.

  for (let key in scores) {
    if (scores[key] === 'A+') {
      scores[key] = 4.5;
    } else if (scores[key] === 'A') {
      scores[key] = 4;
    } else if (scores[key] === 'B+') {
      scores[key] = 3.5;
    } else if (scores[key] === 'B') {
      scores[key] = 3;
    } else if (scores[key] === 'C+') {
      scores[key] = 2.5;
    } else if (scores[key] === 'C') {
      scores[key] = 2;
    } else if (scores[key] === 'D+') {
      scores[key] = 1.5;
    } else if (scores[key] === 'D') {
      scores[key] = 1;
    } else if (scores[key] === 'F') {
      scores[key] = 0;
    }
  }

이제 배열 requiredClasses의 요소들이 scores 객체의 key가 되어야 하므로 scores[requiredClasses의 요소] = value; 의 코드를 작성하면 scores 객체에 추가할 수 있다.

requiredClasses의 요소가 이미 scores에 key로 존재하면 value가 할당되어있는 상태이므로, 중복되지 않는 요소만 객체에 추가해주면 된다. 이때 .forEach() method를 사용하여 배열의 모든 요소를 순회한다.
중복되지 않은 요소는 value가 할당되어 있지 않기 때문에 출력하면 undefined 라고 나온다.

그러므로 scores[requiredClasses의 요소] = undefined 를 찾아 scores 객체에 추가하면 된다.

requiredClasses.forEach(element => {
  if (scores[element] === undefined) {
    scores[element] = 0;
  }
})

최종 작성된 함수는 아래와 같다.

const convertExamResult = (scores, requiredClasses) => {
  // scores: object, requiredClasses: array
  for (let key in scores) {
    if (scores[key] === 'A+') {
      scores[key] = 4.5;
    } else if (scores[key] === 'A') {
      scores[key] = 4;
    } else if (scores[key] === 'B+') {
      scores[key] = 3.5;
    } else if (scores[key] === 'B') {
      scores[key] = 3;
    } else if (scores[key] === 'C+') {
      scores[key] = 2.5;
    } else if (scores[key] === 'C') {
      scores[key] = 2;
    } else if (scores[key] === 'D+') {
      scores[key] = 1.5;
    } else if (scores[key] === 'D') {
      scores[key] = 1;
    } else if (scores[key] === 'F') {
      scores[key] = 0;
    }
  }

  requiredClasses.forEach(element => {
    if (scores[element] === undefined) {
      scores[element] = 0;
    }
  })
  return scores;
}
profile
Hello

0개의 댓글