Javascript如何获取嵌套数组对象中chartData的value最大值
实现思路
将所有嵌套在chartData中的value字段值提取为一维数组,再取数组最大值,封装为通用函数可适配不同字段名的同类需求。
通用实现代码
/** * 提取嵌套数组中指定字段的最大值 * @param {Array} arr 原始外层数组 * @param {String} nestedKey 内层嵌套数组的属性名 * @param {String} valueKey 要提取最大值的数值字段名 * @returns {Number|null} 最大值,无有效值时返回null */ function getMaxNestedValue(arr, nestedKey, valueKey) { const allValues = arr.flatMap(item => item[nestedKey].map(subItem => subItem[valueKey])); return allValues.length ? Math.max(...allValues) : null; } // 调用示例 const maxValue = getMaxNestedValue(Application, 'chartData', 'value'); console.log(maxValue); // 输出 60
低版本兼容实现(不依赖ES6+的flatMap语法)
如果运行环境不支持flatMap,可改用reduce实现相同逻辑:
function getMaxNestedValue(arr, nestedKey, valueKey) { const allValues = arr.reduce((result, current) => { return result.concat(current[nestedKey].map(sub => sub[valueKey])); }, []); return allValues.length ? Math.max.apply(null, allValues) : null; }
说明
- 方法已处理边界情况:如果所有嵌套数组都没有有效值,会返回
null避免得到-Infinity的异常结果 - 通用性强,后续如果嵌套数组名、数值字段名变更,只需修改调用时传入的后两个参数即可,无需调整函数内部逻辑
内容的提问来源于stack exchange,提问作者lazyCoder
相关产品推荐
相关产品推荐

