首页 > 解决方案 > 在对象中找到最大值 - React Hook

问题描述

我在 React 中有一个包含以下值的状态:

{
   income 1 : 500,
   income 2 : 300,
   income 3 : 1000
}

这个状态扩展,客户可以在状态中添加或删除行,所以我需要动态的找到Object中值较高的key/value。

我试过这个,但它只检索第一个键/值:

export const maxIncome = (userWalletIncomes) => {
    for (const [key, value] of Object.entries(userWalletIncomes)) {
        return `${key} : ${Math.max(value)}`
    }
}

任何想法 ?

标签: reactjs

解决方案


它返回第一个值的原因是因为您没有任何条件逻辑阻止返回第一次发生。

要解决这个问题,您需要首先找到具有最大值的记录并将其返回,并且仅在最后返回。

export const maxIncome = (userWalletIncomes) => {
    let maxValue = 0;
    let maxKey = '';
    for (const [key, value] of Object.entries(userWalletIncomes)) {
        if(value > maxValue) {
          maxValue = value;
          maxKey = key
        }
    }
    return `${maxKey} : ${maxValue}`
}

上面的代码可以进一步简化,但它应该清楚地表明您需要在返回之前先找到最大值。


推荐阅读