You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何提取嵌套对象数组中的最低price值,是否可使用reduce方法?

回答

完全可以使用reduce方法实现需求,以下是具体实现方案:

核心思路

  1. 先通过Object.values()(或你提到的Object.entries())取出对象中所有的属性值,也就是所有包含price的对象数组
  2. 外层reduce遍历所有数组,初始最小值设置为正无穷Infinity,保证任何实际价格都能替换初始值
  3. 内层reduce遍历每个数组的所有元素,计算当前数组的最小price,再和全局最小值比较更新即可

代码实现

基础实现(两层reduce)

const obj = {
  small: [{ price: 10 }, { price: 90 }],
  medium: [{ price: 33 }, { price: 8 }],
  large: [{ price: 34 }, { price: 44 }]
}

const minPrice = Object.values(obj).reduce((globalMin, currentArr) => {
  // 计算当前数组的最小price
  const arrMin = currentArr.reduce((min, item) => Math.min(min, item.price), Infinity)
  // 更新全局最小值
  return Math.min(globalMin, arrMin)
}, Infinity)

console.log(minPrice) // 输出 8

基于你给出的Object.entries(obj)开头的实现

如果需要从Object.entries(obj)开始写,只需要调整外层reduce的取值逻辑即可:

const minPrice = Object.entries(obj).reduce((globalMin, [key, currentArr]) => {
  const arrMin = currentArr.reduce((min, item) => Math.min(min, item.price), Infinity)
  return Math.min(globalMin, arrMin)
}, Infinity)

简化写法(先扁平提取所有price再reduce)

如果允许结合其他数组方法,可以先把所有price提取为一维数组,再用reduce求最小值:

const minPrice = Object.values(obj)
  .flatMap(arr => arr.map(item => item.price))
  .reduce((min, price) => Math.min(min, price), Infinity)

以上所有方法运行后都能得到预期结果8。

内容的提问来源于stack exchange,提问作者Michael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 07:39:03