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

根据子对象的i属性查找其父对象的i属性

通过子元素的i属性查找父元素的i属性

给定如下嵌套结构的JS对象数组:

const arr = [
  {
    "w": 2,
    "h": 2,
    "x": 0,
    "y": 0,
    "i": "SankeyChart_3_ae2cc",
    "moved": false,
    "static": false,
    "children": []
  },
  {
    "w": 6,
    "h": 11,
    "x": 0,
    "y": 2,
    "i": "GridWrapper_6_3d4c1",  // 父元素
    "moved": false,
    "static": false,
    "children": [
      {
        "w": 4,
        "h": 6,
        "x": 0,
        "y": 0,
        "i": "tooltip_119_50038",
        "moved": false,
        "static": false,
        "children": []
      },
      {
        "w": 2,
        "h": 2,
        "x": 1,
        "y": 1,
        "i": "Highchart_135_5de23",  // 子元素
        "moved": false,
        "static": false,
        "children": []
      }
    ]
  }
]

已知子元素的i属性值(如Highchart_135_5de23),需要自动查找其对应父元素的i属性值,无需硬编码父元素ID。


解决方案:递归遍历嵌套结构

针对这种多层嵌套的结构,用递归遍历的方式可以高效定位目标子元素的父节点:遍历每个节点,检查其children数组是否包含目标子元素,若包含则返回当前节点的i;若不包含,则递归遍历该节点的children数组,继续向下查找。

代码实现

function findParentId(items, targetChildId) {
  // 遍历当前层级的所有元素
  for (const item of items) {
    // 检查当前元素的children中是否存在目标子元素
    const hasTargetChild = item.children.some(child => child.i === targetChildId);
    if (hasTargetChild) {
      return item.i;
    }
    // 递归遍历当前元素的children,查找更深层级的父元素
    const nestedParentId = findParentId(item.children, targetChildId);
    if (nestedParentId) {
      return nestedParentId;
    }
  }
  // 未找到对应父元素时返回null
  return null;
}

使用示例

// 查找子元素Highchart_135_5de23的父元素ID
const parentId = findParentId(arr, 'Highchart_135_5de23');
console.log(parentId); // 输出: GridWrapper_6_3d4c1

// 查找不存在的子元素ID时返回null
const nonExistentParentId = findParentId(arr, 'NonExistentId');
console.log(nonExistentParentId); // 输出: null

逻辑说明

  1. 函数接收两个参数:待遍历的元素数组items,以及目标子元素的i值targetChildId。
  2. 遍历当前层级的每个元素,优先检查该元素的children数组是否存在目标子元素。
  3. 找到目标子元素时,直接返回当前元素的i作为父ID。
  4. 若当前元素的children中无目标,则递归调用函数遍历该元素的children数组,继续查找更深层级的父节点。
  5. 整个遍历结束仍未找到目标时,返回null。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 10:22:25