如何访问对象数组中的嵌套数组并求和type为A的value值
如何筛选type为"A"的元素并求和?
嘿,这个需求其实很好解决,咱们用JavaScript数组的几个常用方法组合起来就能搞定。我给你两种常见的实现方式,你可以选自己觉得顺手的来用:
方法一:先展平数组再筛选求和
这种方式逻辑比较直观,先把所有嵌套在array1里的元素合并成一个大数组,再筛选出符合条件的项,最后求和:
// 先定义你的原始数据 const data = [ { id: 1, array1: [ { type: "A", value: 20 }, { type: "B", value: 40 } ] }, { id: 2, array1: [ { type: "A", value: 30 }, { type: "B", value: 100 } ] } ]; // 计算总和 const total = data .flatMap(item => item.array1) // 把所有array1的元素合并成一个数组 .filter(item => item.type === "A") // 只保留type为"A"的元素 .reduce((sum, current) => sum + current.value, 0); // 累加这些元素的value值 console.log(total); // 输出:50
方法二:嵌套reduce直接计算
如果不想展平数组,也可以用两层reduce来实现,外层遍历每个数据项,内层处理当前项的array1:
const data = [ { id: 1, array1: [ { type: "A", value: 20 }, { type: "B", value: 40 } ] }, { id: 2, array1: [ { type: "A", value: 30 }, { type: "B", value: 100 } ] } ]; const total = data.reduce((totalSum, currentItem) => { // 先算出当前item的array1中type为"A"的value总和 const itemSum = currentItem.array1 .filter(subItem => subItem.type === "A") .reduce((subSum, subCurrent) => subSum + subCurrent.value, 0); // 加到总总和里 return totalSum + itemSum; }, 0); console.log(total); // 输出:50
简单说下核心逻辑:不管哪种方法,先通过filter筛选出type === "A"的元素,再用reduce对这些元素的value进行累加就搞定啦。
内容的提问来源于stack exchange,提问作者pham01
相关产品推荐
相关产品推荐

