如何在 array.map() 中返回动态对象键
我只是使用下面的代码从对象的数组中获取最大值,效果很好。
Math.max.apply(Math, class.map(function (o) { return o.Students; }));
其中,类是 array
学生是 key
其中array object
但是每当我需要获得最大值时,我就需要编写完整的代码。因此,我计划将该代码移至如下所示的通用方法。
getMaxValue(array: any[], obj: key) {
return Math.max.apply(Math, array.map(function (o) {
return o.key; // Here I want return students objects
}));
}
哪里, 我传递了一个数组和键(想要获取最大值,例如学生)。因此,每当我想获得最大值时,我只需调用该方法,就像
var maxOfStudents = getMaxValue(class, "Students");
但我不知道如何返回 key
动态地从array.map()
中的对象。怎么办?
最佳答案
使用bracket notation使用对象中的字符串访问属性。
return o[key];
关于javascript - 如何在 array.map() 中返回动态对象键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44719084/