React中如何从对象数组的属性提取最小值?
衬衫列表页展示最低售价的实现方案
核心思路
完全不用依赖options数组的固定位置,就算options里的价格顺序乱了、后续新增了不同价格的选项,计算结果也始终准确——直接从每个衬衫的所有选项中提取价格值,动态计算出最小值即可,完全不受数组元素顺序的影响。
具体实现步骤
1. 修正原始对象的语法问题
你编写的shirt对象存在两处容易导致页面报错的语法问题,调整后的正确结构为:
shirt : { title : "Abc", material : "cotton", options : [ { price: 10, color: "red" }, { price: 20, color: "green" }, { price: 30, color: "blue" } ] }
- 数组元素不需要手动标注
0 :、1 :这类索引,JS数组本身会自动按元素位置维护索引,手动写反而会触发语法错误 - 颜色值
red、green、blue需要用引号包裹为字符串,否则会被识别为未定义的变量,直接抛出引用错误
2. 编写最低价计算逻辑
针对每个衬衫对象,先从options数组中提取所有选项的价格,再用Math.min配合ES6展开运算符得到最小值,比手动写循环判断要简洁高效:
// 提取当前衬衫所有选项的价格值 const allPrices = shirt.options.map(option => option.price); // 计算得到最低售价 const minPrice = Math.min(...allPrices);
3. 集成到原有列表渲染逻辑中
不需要修改原始的衬衫数据结构,把计算逻辑直接写到原有map的渲染回调里即可,完整可运行的代码示例:
shirts.map((shirt) => { // 动态计算当前衬衫的最低售价 const minPrice = Math.min(...shirt.options.map(opt => opt.price)); return ( <div className="shirt-card"> <div>{shirt.title}</div> <div>{shirt.material}</div> <div>From ${minPrice}</div> </div> ) })
边界情况兼容
如果存在某款衬衫options为空数组的情况,直接计算会返回Infinity的异常展示值,需要加判断做兜底:
const minPrice = shirt.options.length ? Math.min(...shirt.options.map(opt => opt.price)) : '暂未上架';
内容的提问来源于stack exchange,提问作者Luis García
相关产品推荐
相关产品推荐

