简体   繁体   English

获取 Object 属性的最大值

[英]Get max value of Object property

I am exploring Javascript but I am still new to it.我正在探索 Javascript 但我还是新手。 I am wondering if it is possible to fetch the max value of kw_req from the obj that I have.我想知道是否可以从我拥有的 obj 中获取kw_req的最大值。

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.我可以遍历 object,将kw_req的值存储在另一个数组中并执行Math.max()但我想知道是否有更直接的方法,比如减少数组或其他任何东西。

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
    }
  }
  ];

Map the values of the object to their kw_req and spread into Math.max : Map object 的值到它们的kw_req并传播到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);

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:由于您的obj值是一个对象数组,因此您需要将内部对象的每个值 map 到它们的kw_req值,然后在使用扩展运算符将结果传递给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: 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM