【问题标题】:Finding the minimum value of a nested object property查找嵌套对象属性的最小值
【发布时间】:2021-03-05 19:54:26
【问题描述】:

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

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

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

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

但是当我对 mission 属性尝试相同的操作时,它会返回 0,而它应该是 3

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

我有什么遗漏或做错了吗?

【问题讨论】:

    标签: javascript object reduce


    【解决方案1】:

    在这种情况下,map 就足够了。

    const yo = {
      one: {
        value: 9,
        mission: 17
      },
      two: {
        value: 18,
        mission: 6
      },
      three: {
        value: 3,
        mission: 4
      },
    }
    
    const total = Object.values(yo).map(({ mission }) => mission);
    console.log(Math.min(...total));

    【讨论】:

    • @Tigran:很不错:)
    【解决方案2】:

    您将0 作为累加器的初始值传递,即t0 小于所有 mission 值。所以你需要传递最大值,即Infinity作为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)

    【讨论】:

    • @KontrolEgo 如果您对它感到满意,请考虑接受答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 2018-07-09
    • 2022-10-14
    • 2021-03-25
    • 1970-01-01
    • 2021-11-14
    • 2019-08-29
    相关资源
    最近更新 更多