You need to enable JavaScript to run this app. 如何根据嵌套JSON选中的深层子项ID获取完整父级链路与关联子级对象
优惠活动
大模型
产品
解决方案
定价
更多

如何根据嵌套JSON选中的深层子项ID获取完整父级链路与关联子级对象

嵌套下拉选中深层子项时获取完整分支对象的实现方案

核心实现逻辑

当前下拉框绑定的是分类的id值,而全量嵌套分类数据已存储在组件内,只需要通过递归遍历嵌套树,顺着选中id向上回溯到该节点所属的顶级根节点,直接返回该节点的原始完整引用即可。该方式不会修改原始数据结构,既能完整保留每个节点下的所有关联子级信息,也会自动过滤和选中节点无层级关联的其他顶级分支。

具体代码实现

1. 递归查找工具方法

在组件类中添加通用递归方法,兼容任意深度的嵌套结构:

/**
 * 按目标id查找对应完整分支的根节点
 * @param tree 全量嵌套分类数组
 * @param targetId 选中的分类id
 * @returns 包含目标节点、全部各级父节点、各节点完整子级的对象树,匹配失败返回null
 */
findTargetRootNode(tree: any[], targetId: number): any {
  if (!tree?.length) return null;

  for (const node of tree) {
    if (node.id === targetId) return node;
    if (node.children?.length) {
      const found = this.findTargetRootNode(node.children, targetId);
      // 子树中匹配到目标,说明当前节点是目标的祖先,直接返回当前节点的原始完整对象
      if (found) return node;
    }
  }
  return null;
}

2. 下拉变更事件处理

修改原有的selectCategory()方法,在选中值变化时获取完整分支对象:

// 组件类中存储结果的属性
selectedFullBranch: any = null;

selectCategory() {
  // 从响应式表单获取当前选中的id
  const selectedId = this.service_category.value;
  if (!selectedId) {
    this.selectedFullBranch = null;
    return;
  }
  // 调用递归方法获取完整分支
  this.selectedFullBranch = this.findTargetRootNode(this.categories, selectedId);
}

效果说明

以示例数据中选中id=3的“Cab Booking”为例,最终selectedFullBranch的返回结构为:

{
  "id": 1,
  "name": "Travel",
  "parent": null,
  "children": [
    {
      "id": 2,
      "name": "Car",
      "parent": 1,
      "children": [
        {
          "id": 3,
          "name": "Cab Booking",
          "parent": 2
        }
      ]
    }
  ]
}

返回结果完全匹配需求:

  • 覆盖选中的深层子项“Cab Booking”
  • 包含该子项的所有各级父节点(Car、Travel)
  • 每个节点完整保留自身所有关联子级,无信息裁剪
  • 自动排除和该分支无关联的其他顶级分类

注意事项

  • 方法直接返回原始数据的对象引用,不对全量分类数据做修改,无额外内存开销
  • 无需根据分类层级调整代码,支持任意深度的嵌套结构
  • 内置空数据、无children叶子节点的边界处理,不会抛出运行时错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.02 08:00:13