js递归查找树形结构中某一个节点的兄弟节点

function findSiblingsById(tree, targetVal,config) {
  const targetKey=config.targetKey
  const children=config.children
  // 递归遍历树形数据结构
  function traverse(nodes) {
    for (let node of nodes) {
      if (node[targetKey] === targetVal) {
        // 找到目标节点,返回其父节点的所有子节点
        return nodes.filter((sibling) => sibling[targetKey] !== targetVal);
      }
      if (node[children]) {
        // 继续遍历子节点
        const result = traverse(node[children]);
        if (result) {
          return result;
        }
      }
    }
  }

  // 调用递归函数,从根节点开始搜索
  return traverse(tree);
}

// 输入数据
const tree = [
  {
    id: 1,
    name: 'Node 1',
    code: '001',
    children: [
      {
        id: 2,
        name: 'Node 2',
        code: '002',
        children: []
      },
      {
        id: 3,
        name: 'Node 3',
        code: '003',
        children: []
      },
      {
        id: 6,
        name: 'Node 6',
        code: '006',
        children: []
      }
    ]
  },
  {
    id: 4,
    name: 'Node 4',
    code: '004',
    children: [
      {
        id: 5,
        name: 'Node 5',
        code: '005',
        children: []
      }
    ]
  }
];

// 查找id为2的兄弟节点
const siblings = findSiblingsById(tree, 2,{targetKey:'id',children:'children'});
console.log(siblings,'兄弟节点');

// 输出
const siblings = [
    {
        "id": 3,
        "name": "Node 3",
        "code": "003",
        "children": []
    },
    {
        "id": 6,
        "name": "Node 6",
        "code": "006",
        "children": []
    }
]

你可能感兴趣的:(数据结构处理,javascript,开发语言)