ExpressJS中如何从嵌套JSON对象获取price字段的最大值
嵌套JSON提取price字段最大值实现方案
你的数据为三层嵌套数组结构:最外层variants数组 → 内层variant_details数组 → 最内层pricing_and_stock数组,price字段存储在最内层对象中,不需要复杂的手动映射逻辑,用以下两种原生JS方法即可实现,无需额外依赖。
方法1:链式flatMap实现(简洁推荐,适配固定嵌套结构)
用flatMap逐层拍平嵌套数组,再提取price值计算最大值即可,代码可读性高:
// 注意:你提供的代码片段最外层缺失开头的{,补全后才是合法JSON结构 const productData = { "variants": [ // 此处为你提供的variants数组完整内容 ] } // 逐层拍平数组,提取所有price值 const priceList = productData.variants .flatMap(variant => variant.variant_details) .flatMap(detail => detail.pricing_and_stock) .map(stockItem => stockItem.price) // 如果需要去重,解开下面这行注释即可 // const uniquePriceList = [...new Set(priceList)] // 计算最大值,空数组时返回默认值0避免出现-Infinity const maxPrice = priceList.length ? Math.max(...priceList) : 0 // 针对你提供的示例数据,输出结果为20000 console.log(maxPrice)
说明:
flatMap为ES2019标准API,Node.js 12及以上版本均原生支持,无需额外兼容处理。
方法2:递归遍历实现(适配不确定嵌套层级的场景)
如果后续数据结构嵌套层级发生变动,可以写通用递归方法,自动遍历所有层级提取price字段,不需要手动调整遍历层级:
function extractAllPrices(target, result = []) { // 遍历数组元素 if (Array.isArray(target)) { target.forEach(item => extractAllPrices(item, result)) return result } // 遍历对象属性 if (target && typeof target === 'object') { if (typeof target.price === 'number') result.push(target.price) Object.values(target).forEach(val => extractAllPrices(val, result)) } return result } const priceList = extractAllPrices(productData) // 去重后算最大值 const uniqueMaxPrice = priceList.length ? Math.max(...new Set(priceList)) : 0
常见失效原因排查
之前手动映射、扁平化操作未生效,通常是以下问题导致:
- 原始JSON格式不合法:你贴出的代码片段最外层缺失开头的
{,直接解析会报语法错误 - 遍历层级遗漏:没有逐层进入
variant_details和pricing_and_stock数组,导致price提取不全 Math.max调用方式错误:直接传入数组而非展开后的数值列表会返回NaN,需要用展开运算符...处理数组参数
内容的提问来源于stack exchange,提问作者Anggiet Bracmatya
相关产品推荐
相关产品推荐

