在处理前端中树形结构的数据时,将多个同级数据根据设计好的路径拼成相应的结构
var arr = ["N0|C0|P0","N0|C0|P1","N0|C1|P2"]; function parsePath(paths){ var map = new Map(); var rootNode = null; for(var j = 0,len=paths.length;j<len;j++){ var parentNode = null; var pathArray = paths[j].split("|"); for(var i = 0;i<pathArray.length;i++){ var id = pathArray[i]; var node = map.get(id); if(node == null){ var obj = {}; obj.flag = id; obj.children = []; map.set(id,obj); node=obj; } if(j==0&&i==0){ rootNode=node; } if(parentNode!=null){ if(contains(parentNode.children,id)){ }else{ parentNode.children.push(node) } } parentNode = node } } console.log(rootNode) } parsePath(arr) function contains(children,b){ for(var i = 0;i<children.length;i++){ var id = children[i].flag; if(id == b){ return true; break; } } return false; }