Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

หาค่าสูงสุดจาก property ของอ็อบเจกต์ - JavaScript

สมมติว่าเรามีอ็อบเจกต์ที่เก็บคะแนนของสถานที่ตามเกณฑ์ต่างๆ:

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

เราต้องเขียนฟังก์ชันที่รับอ็อบเจกต์แบบนี้และคืนค่า key-value pair ที่มีค่าสูงสุด

เช่น สำหรับอ็อบเจกต์นี้ ผลลัพธ์ควรเป็น:

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 }