如何使用最高键值和名称从数组中返回对象——JavaScript?


假设我们有一个对象数组,其中包含一些学生在测试中的成绩信息 −

const students = [
   { name: 'Andy', total: 40 },
   { name: 'Seric', total: 50 },
   { name: 'Stephen', total: 85 },
   { name: 'David', total: 30 },
   { name: 'Phil', total: 40 },
   { name: 'Eric', total: 82 },
   { name: 'Cameron', total: 30 },
   { name: 'Geoff', total: 30 }
];

我们需要编写一个 JavaScript 函数,它接收这样的一个数组并返回一个对象,其中包含总分最高学生的姓名和总分。

因此,对于上面的数组,输出应为 −

{ name: 'Stephen', total: 85 } 

示例

以下是代码 −

const students = [
   { name: 'Andy', total: 40 },
   { name: 'Seric', total: 50 },
   { name: 'Stephen', total: 85 },
   { name: 'David', total: 30 },
   { name: 'Phil', total: 40 },
   { name: 'Eric', total: 82 },
   { name: 'Cameron', total: 30 },
   { name: 'Geoff', total: 30 }
];
const pickHighest = arr => {
   const res = {
      name: '',
      total: -Infinity
   };
   arr.forEach(el => {
      const { name, total } = el;
      if(total > res.total){
         res.name = name;
         res.total = total;
      };
   });
   return res;
};
console.log(pickHighest(students));

输出

这将在控制台中生成以下输出 −

{ name: 'Stephen', total: 85 }

更新于: 01-Oct-2020

617 次浏览

开启你的 职业生涯

通过完成课程获取认证

开始
广告
© . All rights reserved.