[['a'.'b'],
            ['a'.'c'],
            ['d'.'e'.'f'],
            ['d'.'e'.'g'.'h'],
            ['d'.'i']]Copy the code

Convert to the following structure:

[{"name": "a"."child": [{"name": "b"
      },
      {
        "name": "c"}]}, {"name": "d"."child": [{"name": "e"."child": [{"name": "f"
          },
          {
            "name": "g"."child": [{"name": "h"}}]}, {"name": "i"}}]]Copy the code

The solution

// First define a recursive function (tree: result,value: current value,parent: parent value)
function arrpush  (tree, value, parent) {
        tree.forEach((item, index) = > {
            if (item.name === parent) {
            // Check whether it is a layer 1 node
                if (_.find(item.child, { name: value })) {
                    // The current node skipped
                    return;
                } else {
                    // Put the node into the children of the current node
                    item.child.push({
                        name: value,
                        child: []}); }}else {
                if (item.child.length > 0) {
                // Find the location of the node when the child node is not empty, recursive call
                    return this.arrpush(item.child, value, parent); }}}); };// Define app methods to evaluate results
 function app (array) {
        let tree = [];
        array.forEach((item, index) = > {
        // Loop the first layer
            item.forEach((ite, ind) = > {
            // The second loop
                if (ind > 0) {
                    // Not the first node
                    this.arrpush(tree, ite, item[ind - 1]);
                } else {
                    // The first node
                    if (_.find(tree, { name: ite })) {
                        return;
                    } else {
                        tree.push({
                            name: ite,
                            child: []}); }}}); });console.log(tree);
    };
// Run the app method
    app([
            ['a'.'b'],
            ['a'.'c'],
            ['d'.'e'.'f'],
            ['d'.'e'.'g'.'h'],
            ['d'.'i']]);Copy the code

conclusion

First of all, think about how to form a tree structure, what is the relationship between the father and the child. I’m going to use name as the unique identifier here. Consider the connection, and then the recursion, to determine whether the current node exists or not. If blindly added without judgment, it will cause the repetition of nodes. So have proper filtering.