查找嵌套对象属性的最小值 [英] Finding the minimum value of a nested object property

查看:43
本文介绍了查找嵌套对象属性的最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的对象:

I have an object that looks like this:

const yo = {
  one: {
    value: 0,
    mission: 17},
  two: {
    value: 18,
    mission: 3},
  three: {
    value: -2,
    mission: 4},
}

我想在嵌套对象中找到 mission 道具的最小值.此行用于查找嵌套的 value 属性的最小值并返回 -2:

I want to find the minimum value of the mission prop within the nested objects. This line works to find the minimum value of the nested value prop and returns -2:

const total = Object.values(yo).reduce((t, {value}) => Math.min(t, value), 0)

但是当我为 mission 道具尝试同样的事情时,它返回 0 而应该是 3:

But when I try the same thing for the mission prop, it returns 0 when it should be 3:

const total = Object.values(yo).reduce((t, {mission}) => Math.min(t, mission), 0)

我是否遗漏了什么或做错了什么?

Is there something that I am missing or doing wrong?

推荐答案

您正在传递 0 作为累加器的初始值,即 t.0 小于所有 mission 值.所以你需要传递最大值,即 Infinity 作为 reduce() 的第二个参数.

You are passing 0 as the initial value of accumulator i.e t. 0 is less than all the mission values. So you need to pass the greatest value i.e Infinity as second argument of reduce().

const yo = {
  one: {
    value: 0,
    mission: 17},
  two: {
    value: 18,
    mission: 3},
  three: {
    value: -2,
    mission: 4},
}
const total = Object.values(yo).reduce((t, {mission}) => Math.min(t, mission), Infinity);
console.log(total)

这篇关于查找嵌套对象属性的最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆