reactjs - 在对象中找到最大值 - 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)}`
}
}
任何想法 ?
解决方案
它返回第一个值的原因是因为您没有任何条件逻辑阻止返回第一次发生。
要解决这个问题,您需要首先找到具有最大值的记录并将其返回,并且仅在最后返回。
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}`
}
上面的代码可以进一步简化,但它应该清楚地表明您需要在返回之前先找到最大值。
推荐阅读
- java - 我在 Android Studio 中的操作栏的 setHomeAsUpIndicator() 似乎不起作用
- c# - 半透明地形问题(可能是深度缓冲区问题)
- javascript - Ajax 请求没有收到响应
- python - 如何在 django sql 格式中转义引号
- html - 当我添加导航栏时,我的内容下方会添加空格。我该如何删除这个?
- javascript - Electron 收据热敏打印机
- javascript - 无法使用 API 密钥作为环境变量与 asyncData() 中的 Butter CMS 库
- ruby-on-rails - 如何使用 pry 在 Rails 控制台中回滚失败的事务
- tensorflow - ValueError:您正在尝试将包含 5 层的权重文件加载到具有 0 层的模型中
- python - 无法理解 scipy.sparse.csr_matrix 示例