2

How to do return a dynamic object key in array.map()


I'm just getting max value from a array by a object with using this below code which is works good.

Math.max.apply(Math, class.map(function (o) { return o.Students; }));

where, class is an array and Students is an key of that array object


But Whenever I need to get a maximum value, I need write that full code. So I planed to move that code to a common method as below.

 getMaxValue(array: any[], obj: key) {
      return  Math.max.apply(Math, array.map(function (o) { 
               return o.key;  // Here I want return students objects
               }));   
           }

where, I have passing a array and key(which is want to get the max value, like students). So whenever I want to get the max value I just call the method just like

 var maxOfStudents = getMaxValue(class, "Students");

But I don't know how to return the key dynamically from a object in array.map(). how to do it?

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234

1 Answers1

4

Use bracket notation to access the property using a string from an object.

return o[key];
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188