• Array:
[
   {
       id: 1,
       name: "1"
       pid: 0,
   },
   {
       id: 2,
       name: "1-1",
       pid: 1
   },
   {
       id: 3,
       name: "1-1-1",
       pid: 2
   },
   {
       id: 4,
       name: "1-2",
       pid: 1
   },
   {
       id: 5,
       name: "1-2-2",
       pid: 4
   },
   {
       id: 6,
       name: "1-1-1",
       pid: 3
   },
   {
       id: 7,
       name: "2"}]Copy the code

The project is developed in Vue, so add methods to the instance methods of Vue

const install = function(Vue, opts) {/** * [deepClone array/object deep copy] * @param {[type]} source[array/object] * @return {[type]}        [description]
    */
   Vue.prototype.deepClone = function (source) {
       if (!source && typeof source! = ='object') {
           throw new Error('error arguments'.'shallowClone');
       }
       const targetObj = source.constructor === Array ? [] : {};
       for (const keys in source) {
           if (source.hasOwnProperty(keys)) {
               if (source[keys] && typeof source[keys] === 'object') {
                   targetObj[keys] = source[keys].constructor === Array ? [] : {};
                   targetObj[keys] = this.deepClone(source[keys]);
               } else {
                   targetObj[keys] = source[keys]; }}}returntargetObj; }; /** * [structureTreeData builds a tree structure] * @param {[Array]} data [parent-child Array] * @param {[String]} id [node id] * @param {[String]} pid [parent node ID] * @return{} [Object] [tree structure data] * / Vue. Prototype. StructureTreeData =function (data, id = "id", pid = "pid") {
       let pids = [];
       let ids = [];
       data.forEach(item => {
           if(! pids.includes(item.pid)) { pids.push(item.pid); }if(! ids.includes(item.id)) { ids.push(item.id); }}); // Parent dataletparents = data.filter( value => ! ids.includes(value.pid) ); // Child node dataletchildrens = data.filter( value => ids.includes(value.pid) ); // Create tree structure dataletStructure = (parents, childrens) => {parent. forEach(parent => {// childrens) => {// parent => {// childrens. Index) => {// Find a child node corresponding to the parent nodeif(children.pid === parent.id) {// Make a deep copy of the child dataletnewChildrens = this.deepClone(childrens); NewChildrens = newChildrens = newChildrens = newChildrens = newChildrens = newChildrens = newChildrens = newChildrens = newChildrens Structure ([children], newChildrens); // Let the current child be the only parent. Typeof parent.children! Typeof parent.children! = ="undefined"? parent.children.push(children) : (parent.children = [children]); }}); }); }; // Call the constructor structure(parents, childrens);return parents;
   };
}
export default {
   install
}
Copy the code