查找嵌套对象的最小值 属性
Finding the minimum value of a nested object property
我有一个看起来像这样的对象:
const yo = {
one: {
value: 0,
mission: 17},
two: {
value: 18,
mission: 3},
three: {
value: -2,
mission: 4},
}
我想在嵌套对象中找到 mission
属性的最小值。此行用于查找嵌套 value
属性和 returns -2
:
的最小值
const total = Object.values(yo).reduce((t, {value}) => Math.min(t, value), 0)
但是当我对 mission
道具尝试同样的事情时,它 returns 0
而它应该是 3
:
const total = Object.values(yo).reduce((t, {mission}) => Math.min(t, mission), 0)
我是否遗漏或做错了什么?
您正在传递 0
作为累加器的初始值,即 t
。 0
小于所有 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)
在这种情况下,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));
我有一个看起来像这样的对象:
const yo = {
one: {
value: 0,
mission: 17},
two: {
value: 18,
mission: 3},
three: {
value: -2,
mission: 4},
}
我想在嵌套对象中找到 mission
属性的最小值。此行用于查找嵌套 value
属性和 returns -2
:
const total = Object.values(yo).reduce((t, {value}) => Math.min(t, value), 0)
但是当我对 mission
道具尝试同样的事情时,它 returns 0
而它应该是 3
:
const total = Object.values(yo).reduce((t, {mission}) => Math.min(t, mission), 0)
我是否遗漏或做错了什么?
您正在传递 0
作为累加器的初始值,即 t
。 0
小于所有 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)
在这种情况下,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));