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

如何在嵌套对象数组中获取末尾对象并更新属性(无需ID等参数)

如何在未知对象属性值的情况下修改嵌套对象数组的最深层叶子节点属性

给定一个嵌套的对象数组,我们需要在不知道任何对象ID或属性值的前提下,找到整个结构里层级最深的叶子节点(没有子节点的对象),并修改它的属性。以下是具体实现方案:

实现思路

通过递归遍历整个嵌套数组,追踪每个节点的层级深度:

  1. 记录遍历过程中遇到的最大层级深度
  2. 从后往前遍历每个层级的节点,确保同深度的节点中,最后一个会被优先选中
  3. 找到最深层级的叶子节点后,直接修改其属性

代码实现

首先定义一个递归函数来定位目标节点:

function findDeepestLastLeaf(arr) {
  let deepestNode = null;
  let maxDepth = -1;

  function traverse(nodes, currentDepth) {
    // 从后往前遍历同层级节点,确保最后一个同深度节点被选中
    for (let i = nodes.length - 1; i >= 0; i--) {
      const node = nodes[i];
      // 更新最深节点记录
      if (currentDepth > maxDepth) {
        maxDepth = currentDepth;
        deepestNode = node;
      }
      // 递归遍历子节点(如果存在)
      if (node.children && node.children.length > 0) {
        traverse(node.children, currentDepth + 1);
      }
    }
  }

  traverse(arr, 0);
  return deepestNode;
}

然后使用这个函数修改目标属性:

// 示例数组
const arr = [ 
  {id: 1, comment:'parent 01', parentId:null, reply:true, children:[
    {id: 11, comment:'child', reply:true, parentId:1, children:[
      {id: 21, comment:'super child ', reply:true,parentId:11 }
    ] }
  ] }, 
  {id: 2, comment:'parent 02', reply:true, parentId:null } 
];

// 找到目标节点并修改属性
const targetNode = findDeepestLastLeaf(arr);
if (targetNode) {
  targetNode.reply = false;
}

console.log(targetNode);
// 输出:{id: 21, comment:'super child ', reply:false, parentId:11 }

补充说明

如果你的需求是找到遍历顺序中的最后一个叶子节点(而非最深层级),可以修改遍历逻辑为从前往后遍历,只要遇到叶子节点就更新记录:

function findLastLeaf(arr) {
  let lastLeaf = null;
  let maxDepth = -1;

  function traverse(nodes, currentDepth) {
    for (const node of nodes) {
      if (!node.children || node.children.length === 0) {
        if (currentDepth >= maxDepth) {
          maxDepth = currentDepth;
          lastLeaf = node;
        }
      } else {
        traverse(node.children, currentDepth + 1);
      }
    }
  }

  traverse(arr, 0);
  return lastLeaf;
}

使用这个函数时,示例数组中最后一个叶子节点是id:2的对象,修改后会把它的reply设为false。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 13:10:33