Moment For Technology

Front - end build tree menu wrapper class

Posted on Aug. 11, 2023, 6:43 a.m. by Alisha Chaudhari
Category: javascript Tag: javascript The front end

Background passed is a list of data, the list of data sort may be disorderly, root parent set ID is 0, but it is possible to randomly delete one of them, resulting in this data parent set ID can not be traced back to 0, temporarily so write, there may be a better method!

Export const create = function (config) {@param list */ this.clearnopid = function (list) { const ids = []; const arr = []; for (let i = 0; i  list.length; i++) { let item = list[i]; let flag = this.hasParents(list, item, ids); if (flag) { ids.push(item.id); let obj={}; for(let key in config.props){ obj[key]=item[config.props[key]]; } arr.push(obj); } else { list.splice(i, 1); i--; } } return this.createTree(arr, []); } /** * Check whether the root menu is 0 */ this.hasparents = function (list, node, ids) {let flag = false; if (node.pid === 0 || ids.indexOf(node.id) ! == -1) { flag = true; } else { for (let i = 0; i  list.length; i++) { let item = list[i]; if (item.id === node.pid) { flag = this.hasParents(list, item, ids); } } } return flag; } @param list */ this.createtree = function (list, data) {for (let I = 0; i  list.length; i++) { let item = list[i]; If (item.pid == 0) {data.push(item); list.splice(i, 1); i--; } else { let flag = this.findChild(data, item); if (flag) { list.splice(i, 1); i--; } } } if (list.length  0) { data = this.createTree(list, data); } return data; } /** * Find parent set ID * @param list * @param node */ this.findChild = function (list, node) {let flag = false; for (let i = 0; i  list.length; i++) { let item = list[i]; if (item.id === node.pid) { item.children = item.children || []; item.children.push(node); flag = true; break; } else { if (item.children) { flag = this.findChild(item.children, node); if (flag) { break; } } } } return flag; } // Call const data = this.clearnopid (config.list); return data; }; Const config = {list: [], props: {id: 'props ', // must name: 'pid', // must name: 'menuName', // Optional, can name:' menuState ': }} this.menuNodes = createdTree.create(config);
Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.