You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何访问对象数组中的嵌套数组并求和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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 21:37:40