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

编写递归函数统计嵌套数组中selected为true的对象并添加统计字段

实现嵌套数组的选中统计与子节点计数递归函数

需求说明

需要编写一个JavaScript递归函数,完成两个核心操作:

  1. 统计嵌套数组中所有selected属性为true的对象总数
  2. 为每个节点添加selectedChildren字段,记录其所有下属(直接+间接)节点中selected为true的对象数量

示例数据

const sampleData = [
  {
    id: 1,
    selected: false,
    children: [
      { id: 11, selected: true, children: [] },
      { id: 12, selected: false, children: [{ id: 121, selected: true, children: [] }] }
    ]
  },
  {
    id: 2,
    selected: true,
    children: [{ id: 21, selected: false, children: [] }]
  }
];

函数实现

function countSelectedNodes(nodes) {
  let totalSelected = 0;

  nodes.forEach(node => {
    // 递归处理子节点,获取子节点的选中总数(同时子节点会被添加selectedChildren)
    const childCount = node.children ? countSelectedNodes(node.children) : 0;
    // 给当前节点赋值子节点选中数
    node.selectedChildren = childCount;
    // 累加当前节点的选中状态和子节点的选中总数
    totalSelected += node.selected ? 1 : 0;
    totalSelected += childCount;
  });

  return totalSelected;
}

逻辑说明

  • 函数接收节点数组,返回整个结构中selected为true的总数量
  • 遍历每个节点时,先递归处理其children数组,递归过程会自动给子节点添加selectedChildren字段
  • 为当前节点设置selectedChildren为子节点的选中总数
  • 累加当前节点自身的选中状态(true则加1)和子节点的选中总数,得到当前层级的总选中数
  • 最终向上返回累计的总数

使用示例与预期结果

// 调用函数
const totalSelected = countSelectedNodes(sampleData);

// 输出总选中数
console.log(totalSelected); // 输出:3

// 处理后的节点结构示例
console.log(sampleData[0].selectedChildren); // 输出:2(对应id11和121)
console.log(sampleData[0].children[1].selectedChildren); // 输出:1(对应id121)
console.log(sampleData[1].selectedChildren); // 输出:0

注意:该函数会直接修改原数据,如果需要保留原始数据,建议先对输入数组进行深拷贝,比如使用const clonedData = JSON.parse(JSON.stringify(sampleData))后再传入函数。

内容的提问来源于stack exchange,提问作者Cleiton Freitas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 07:10:28