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

JavaScript如何按嵌套层级为对象数组元素添加className属性

嵌套对象数组层级属性添加方案

你的现有代码仅遍历了顶层数组,没有对深层的children做递归处理,同时错误将数组索引作为层级参数使用,所以无法实现嵌套层级的属性添加。

实现思路

  • 封装递归处理函数,入参为待处理的节点数组和当前嵌套层级,层级默认值为0
  • 遍历每个节点时,按照当前层级生成对应的className属性
  • 如果当前节点存在子节点,递归调用处理函数处理子节点数组,层级参数加1
  • 以下默认实现为纯函数,不会修改原数组

完整代码实现

// 递归添加className的工具函数
const processTree = (nodeList, currentLevel = 0) => {
  return nodeList.map(node => {
    // 生成当前节点的className
    const className = currentLevel === 0 
      ? "level-0 group" 
      : `level-${currentLevel} leaf`;
    
    // 递归处理子节点
    const processedChildren = node.children.length 
      ? processTree(node.children, currentLevel + 1)
      : node.children;

    // 返回处理后的新节点
    return {
      ...node,
      className,
      children: processedChildren
    };
  });
};

// 调用函数得到最终结果
const result = processTree(arr1);

如果不需要保留原数组,想要直接修改原对象节省内存,可以使用如下写法:

const processTreeMutate = (nodeList, currentLevel = 0) => {
  nodeList.forEach(node => {
    node.className = currentLevel === 0 ? "level-0 group" : `level-${currentLevel} leaf`;
    if (node.children.length) {
      processTreeMutate(node.children, currentLevel + 1);
    }
  });
};

processTreeMutate(arr1);
// 处理完成后arr1就是添加了className的目标结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 00:09:02