prakashchhetri
prakashchhetri

Reputation: 1816

Get max value of Object property

I am exploring Javascript but I am still new to it. I am wondering if it is possible to fetch the max value of kw_req from the obj that I have.

I can loop through the object, store the values of kw_req in another array and do Math.max() but I am wondering if there is anything more straight forward, like reducing the array or anything.

Any help would be appreciated.

let obj = [
    {
    "Jan" :{
      active: "true",
      kw_req: 1.8807145148137498,
      kw_to_maintain: 22.568574177764997,
      kw_to_raise: 68.38277975862793,
      month: "Feb",
      temperature: 23,
      temperature_coeff: 0.671
    },
    "Feb": {
      active: "true",
      kw_req: 4,
      kw_to_maintain: 22.568574177764997,
      kw_to_raise: 68.38277975862793,
      month: "Feb",
      temperature: 23,
      temperature_coeff: 0.671
    },
    "Mar": {
      active: "true",
      kw_req: 1,
      kw_to_maintain: 22.568574177764997,
      kw_to_raise: 68.38277975862793,
      month: "Feb",
      temperature: 23,
      temperature_coeff: 0.671
    }
  }
  ];

Upvotes: 0

Views: 63

Answers (2)

Nick
Nick

Reputation: 147146

Since your obj value is an array of objects, you need to map each of the values of the internal objects to their kw_req value, then flatten the result before passing it to Math.max using the spread operator:

let obj = [
    {
    "Jan" :{
      active: "true",
      kw_req: 1.8807145148137498,
      kw_to_maintain: 22.568574177764997,
      kw_to_raise: 68.38277975862793,
      month: "Feb",
      temperature: 23,
      temperature_coeff: 0.671
    },
    "Feb": {
      active: "true",
      kw_req: 4,
      kw_to_maintain: 22.568574177764997,
      kw_to_raise: 68.38277975862793,
      month: "Feb",
      temperature: 23,
      temperature_coeff: 0.671
    },
    "Mar": {
      active: "true",
      kw_req: 1,
      kw_to_maintain: 22.568574177764997,
      kw_to_raise: 68.38277975862793,
      month: "Feb",
      temperature: 23,
      temperature_coeff: 0.671
    }
  }
];

const max_kw = Math.max(...obj.flatMap(o => Object.values(o).map(m => m.kw_req)));
console.log(max_kw)

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370699

Map the values of the object to their kw_req and spread into Math.max:

let obj=[{Jan:{active:"true",kw_req:1.8807145148137498,kw_to_maintain:22.568574177764997,kw_to_raise:68.38277975862793,month:"Feb",temperature:23,temperature_coeff:.671},Feb:{active:"true",kw_req:4,kw_to_maintain:22.568574177764997,kw_to_raise:68.38277975862793,month:"Feb",temperature:23,temperature_coeff:.671},Mar:{active:"true",kw_req:1,kw_to_maintain:22.568574177764997,kw_to_raise:68.38277975862793,month:"Feb",temperature:23,temperature_coeff:.671}}];
  
const max = Math.max(
  ...Object.values(obj[0])
    .map(val => val.kw_req)
);
console.log(max);

Upvotes: 1

Related Questions