JavaScript converts flat data into tree structure data, and converts tree structure into flat data

Convert flat data to tree data

The following is an example function that converts flat data into tree-structured data using JavaScript:

function flatToTree(flatData, idKey, parentKey, childrenKey) {
    
    
  const tree = [];
  const map = {
    
    };

  // 将所有节点存储到map中
  flatData.forEach(node => {
    
    
    map[node[idKey]] = node;
    node[childrenKey] = [];
  });

  // 遍历所有节点,将其添加到对应的父节点下
  flatData.forEach(node => {
    
    
    const parent = map[node[parentKey]];
    if (parent) {
    
    
      parent[childrenKey].push(node);
    } else {
    
    
      tree.push(node);
    }
  });

  return tree;
}

The function accepts four parameters:

  • flatData: Flat layer data, that is, an array containing all nodes.
  • idKey: The key name of the node ID.
  • parentKey: The key name of the parent node ID.
  • childrenKey: The key name of the child node array.

The function first creates an empty array of tree structures treeand an empty nodemap object map. Then iterate through all the nodes, store them into mapa , and add an empty array of children to each node. Then traverse all nodes again, add them to the corresponding parent node, if there is no parent node, add it to the treearray. Finally return treethe array.

Example usage:

const flatData = [
  {
    
     id: 1, name: 'Node 1', parentId: null },
  {
    
     id: 2, name: 'Node 2', parentId: 1 },
  {
    
     id: 3, name: 'Node 3', parentId: 1 },
  {
    
     id: 4, name: 'Node 4', parentId: 2 },
  {
    
     id: 5, name: 'Node 5', parentId: 2 },
  {
    
     id: 6, name: 'Node 6', parentId: 3 },
  {
    
     id: 7, name: 'Node 7', parentId: null },
];

const treeData = flatToTree(flatData, 'id', 'parentId', 'children');
console.log(treeData);

Output result:

[
  {
    
    
    "id": 1,
    "name": "Node 1",
    "parentId": null,
    "children": [
      {
    
    
        "id": 2,
        "name": "Node 2",
        "parentId": 1,
        "children": [
          {
    
    
            "id": 4,
            "name": "Node 4",
            "parentId": 2,
            "children": []
          },
          {
    
    
            "id": 5,
            "name": "Node 5",
            "parentId": 2,
            "children": []
          }
        ]
      },
      {
    
    
        "id": 3,
        "name": "Node 3",
        "parentId": 1,
        "children": [
          {
    
    
            "id": 6,
            "name": "Node 6",
            "parentId": 3,
            "children": []
          }
        ]
      }
    ]
  },
  {
    
    
    "id": 7,
    "name": "Node 7",
    "parentId": null,
    "children": []
  }
]

Convert tree data to flat data
The following is a JavaScript function that recursively converts tree data to flat data:

function flattenTreeData(treeData, parentId = null, result = []) {
    
    
  treeData.forEach(node => {
    
    
    const {
    
     id, children, ...rest } = node;
    result.push({
    
     id, parentId, ...rest });
    if (children) {
    
    
      flattenTreeData(children, id, result);
    }
  });
  return result;
}

The function accepts three parameters:

  • treeData: Tree structure data, must be an array.
  • parentId: ID of the parent node of the current node, the initial value is null.
  • result: The array used to store flat layer data, the initial value is [].

The function first traverses each node of the tree structure data, converts it into a flat data format, and adds it to resultthe array. Then, if the node has child nodes, call flattenTreeDatathe function recursively to convert the child nodes into flat data format and add them to resultthe array.

Finally, the function returns resultan array containing the flat data format of all nodes.

Guess you like

Origin blog.csdn.net/weixin_41897680/article/details/131409494