JSで树状データ構造の特定の节点の父、兄弟、子节点を取得する方法

特定の节点のすべての父节点を取得する関数:

  function getAllParentNodes(list, id) {
    for (let i in list) {
      if (list[i].id === id) {
        return list[i].children.map(v => v.id !== id ? v : null);
      }
      if (list[i].children && list[i].children.length > 0) {
        const nodes = getAllParentNodes(list[i].children, id);
        return nodes ? nodes : list[i].children;
      }
    }
    return [];
  }

特定の节点の兄弟节点を取得する関数:

  function getBrotherNodes(list, id) {
    for (let i in list) {
      if (list[i].id === id) {
        return list.filter(v => v.id !== id);
      }
      if (list[i].children && list[i].children.length > 0) {
        const nodes = getBrotherNodes(list[i].children, id);
        return nodes ? nodes : [];
      }
    }
    return [];
  }

特定の节点のすべての子节点を取得する関数:

  function getAllChildrenNodes(list, id, arr = []) {
    for (let i in list) {
      if (list[i].id === id) {
        arr.push(list[i]);
        if (list[i].children && list[i].children.length > 0) {
          getChild(list[i].children, arr);
        }
      } else {
        if (list[i].children && list[i].children.length > 0) {
          getAllChildrenNodes(list[i].children, id, arr);
        }
      }
    }
    return arr.filter(v => v.id !== id);
  }

  function getChild(list, arr) {
    list.forEach(v => {
      arr.push(v);
      if (v.children) {
        getChild(v.children, arr);
      }
    });
  }

データ例:

  let list = [
    {
      label: '最外层1',
      id: '1',
      children: [
        {
          label: '第二层1',
          id: '1-1',
          children: [
            {
              label: '第三层1',
              id: '1-1-1',
              children: [
                { label: '第四层1', id: '1-1-1-1' },
                { label: '第四层2', id: '1-1-1-2' }
              ]
            },
            {
              label: '第三层2', id: '1-1-2' 
            },
            {
              label: '第三层3', id: '1-1-3'
            }
          ]
        },
        {
          label: '第二层2', id: '1-2'
        }
      ]
    }
  ];

例: id '1-1'を基準とした节点

let children = getAllChildrenNodes(list, '1-1');
let parents = getAllParentNodes(list, '1-1');
let brothers = getBrotherNodes(list, '1-1');

console.log('子节点:', children);
console.log('父节点:', parents);
console.log('兄弟节点:', brothers);

上記の例において、

  • 子节点は「1-1-1」、「1-1-2」、「1-1-3」
  • 父节点は「1」
  • 兄弟节点は「1-1-2」、「1-1-3」

6月21日 22:22 投稿