Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

객체 속성 값에서 가장 높은 숫자 반환 – JavaScript

<시간/>

다음과 같은 일부 기준에 대한 속성 등급을 포함하는 개체가 있다고 가정합니다.

const rating = {
   "overall": 92,
   "atmosphere": 93,
   "cleanliness": 94,
   "facilities": 89,
   "staff": 94,
   "security": 92,
   "location": 88,
   "valueForMoney": 92
}

우리는 그러한 객체 하나를 받아서 가장 높은 값을 갖는 키-값 쌍을 반환하는 JavaScript 함수를 작성해야 합니다.

예를 들어, 바로 이 객체에 대해 출력은 -

여야 합니다.
const output = {
   "staff": 94
};

예시

다음은 코드입니다 -

const rating = {
   "overall": 92,
   "atmosphere": 93,
   "cleanliness": 94,
   "facilities": 89,
   "staff": 94,
   "security": 92,
   "location": 88,
   "valueForMoney": 92
}
const findHighest = obj => {
   const values = Object.values(obj);
   const max = Math.max.apply(Math, values);
   for(key in obj){
      if(obj[key] === max){
         return {
            [key]: max
         };
      };
   };
};
console.log(findHighest(rating));

출력

이것은 콘솔에 다음과 같은 출력을 생성합니다 -

{ cleanliness: 94 }