'Javascript tree adding and deleting object or children by key in array

I'm trying to make file stucture tree and got some problems. And then draw it with ant design tree. Having some problems with functions to update data on my react component.

  {
    key: "1",
    title: "All spaces",
    type: "rootFolder",
    children: [
      {
        key: "2",
        title: "Space_1",
        type: "space",
        children: [
          { key: "3", title: "page_1", isLeaf: true, type: "page" },
          { key: "4", title: "page_2", isLeaf: true, type: "page" }
        ]
      }
    ]
  },
  {
    key: "8",
    title: "User folders",
    type: "rootFolder",
    children: [
      {
        key: "9",
        title: "User_folder_1",
        children: [
          {
            key: "10",
            title: "Space_3",
            type: "space",
            children: [
              { key: "11", title: "page_5", isLeaf: true, type: "page" },
              { key: "12", title: "page_6", isLeaf: true, type: "page" }
            ]
          },
        ]
      }
    ]
  }
];

I got tree like that, and need two functions 1) will get tree, node key to appen children, new children key it should add new children object to children of node and return tree 2) function that will get tree, object id to delete and will return new tree without deleted objects and their childrens. Much thanks for Help!



Solution 1:[1]

There are three functions that could help you.

  1. Finding node by key and appending newNode to children and returning updated tree.
const addNodeByKeyToChildren = (tree, nodeKey, newNode) => {
    for (const node of tree) {
        if (node.key === nodeKey) {
            node.children = node?.children || [];
            node.children?.push(newNode);
            return tree;
        }

        if (node.children) {
            node.children = addNodeByKeyToChildren(node.children, nodeKey, newNode);
        }
    }

    return tree;
};

  1. Finding node by key and returning it or false, if it's not found.
const findNodeByKey = (tree, nodeKey) => {
    for (const node of tree) {
        if (node.key === nodeKey) {
            return node;
        }

        if (node.children) {
            const foundNode = findNodeByKey(node.children, nodeKey);
            if (foundNode) return foundNode;
        }
    }

    return false;
};

  1. Removing node by key and returning updated tree.
const removeNodeByKey = (tree, nodeKey) => {
    for (const node of tree) {
        if (node.key === nodeKey) {
            return tree.filter(el => el.key !== nodeKey);
        }

        if (node.children) {
            node.children = removeNodeByKey(node.children, nodeKey);
        }
    }

    return tree;
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1