[英]Get max value of Object property
我正在探索 Javascript 但我还是新手。 我想知道是否可以从我拥有的 obj 中获取kw_req
的最大值。
我可以遍历 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: 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 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);
由于您的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.