藍山帝景
2023-08-24 21:04:27
我有一個看起來像這樣的對象:const yo = { one: { value: 0, mission: 17}, two: { value: 18, mission: 3}, three: { value: -2, mission: 4},}mission我想找到嵌套對象中 prop的最小值。此行用于查找嵌套 prop 的最小值value并返回-2:const total = Object.values(yo).reduce((t, {value}) => Math.min(t, value), 0)但是當我對 prop 嘗試同樣的操作時mission,它會0在應該返回的時候返回3:const total = Object.values(yo).reduce((t, {mission}) => Math.min(t, mission), 0)我是否遺漏或做錯了什么?
2 回答

森林海
TA貢獻2011條經驗 獲得超2個贊
在這種情況下,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));

弒天下
TA貢獻1818條經驗 獲得超8個贊
0您將作為累加器 ie 的初始值傳遞t。0小于所有mission值。因此,您需要傳遞最大值 ieInfinity作為 的第二個參數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)
添加回答
舉報
0/150
提交
取消