从对象属性值返回最大值 - 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 }
广告