如何从嵌套JSON数组中获取points属性的最大值
解决方案
原有代码问题说明
你写的代码存在几处错误:
- 用
for...in遍历数组长度属于错误用法,for...in适用于对象属性遍历,数组遍历建议用基础for循环或for...of - 你的数据结构里不存在
data.data属性,一级分类数组是data.children - 缺少points属性存在性判断、最大值比较的逻辑
基础循环实现(兼容性好)
// 初始值设为负无穷,保证所有有效数值都能参与比较 let maxPoints = -Infinity; // 遍历两个一级分类 for (let i = 0; i < data.children.length; i++) { const currentCategory = data.children[i]; // 遍历分类下的所有子节点 for (let j = 0; j < currentCategory.children.length; j++) { const childNode = currentCategory.children[j]; // 跳过没有points属性的节点,比如样例中的SYS if ('points' in childNode) { if (childNode.points > maxPoints) { maxPoints = childNode.points; } } } } console.log(maxPoints); // 样例数据输出结果为9
简洁函数式实现
const maxPoints = data.children // 展开所有分类的子节点为一维数组 .flatMap(category => category.children) // 过滤出带有points属性的节点 .filter(node => 'points' in node) // 求最大值 .reduce((maxVal, current) => Math.max(maxVal, current.points), -Infinity); console.log(maxPoints); // 样例数据输出结果为9
两种实现对样例数据的输出结果都是9,符合你要找两个分类下所有子节点points最大值的需求。如果没有任何有效points值,返回结果为-Infinity,你可以根据业务需求增加兜底处理逻辑。
内容的提问来源于stack exchange,提问作者F Nasir
相关产品推荐
相关产品推荐

