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?

5
  • 2
    hmm... o[key] ? Commented Jun 23, 2017 at 10:26
  • String key instead of object and o[key] should do the trick. Commented Jun 23, 2017 at 10:26
  • @StanislavKvitash What will I do if I want two key's? Commented Jun 23, 2017 at 10:37
  • @RameshRajendran that's another question :) Commented Jun 23, 2017 at 10:53
  • @StanislavKvitash . yupe. I have asked that for a new question : stackoverflow.com/questions/44719783/… Commented Jun 23, 2017 at 11:00

1 Answer 1

4

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

return o[key];
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.