假设我们有一个对象,其中包含对像这样的某些条件的属性评分-
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 }