JS converts data with parent-child relationships into tree-structured data
For example, the following basic data:
Let Alldatas =[{ID:3, Name:' BBBB ', Parendid:1}, {ID:2, Name:' AAAAA ', Parendid:2}, {ID:4, Name:' CCCCC ', Parendid:1}, {ID:5, Name:' DDDDD ', Parendid:4}, {ID:6, Name:' Eeeee ', Parendid:4}, {ID:7, Name:' FFFF ', Parendid:6}, {ID:8, Name:' GGGGG ', Parendid:3}, {ID:9, Name:' Hhhhh ', Parendid:5}, {ID:10, Name:' JJJJ ', Parendid:6 }];
You need to convert to the following data format, as follows:
[ { "ID": 3, "Name": "BBBB", "Children": [ { "ID": 8, "Name": "GGGGG", "Children": [] } ] }, { "ID": 4, "Name": "CCCCC", "Children": [ { "ID": 5, "Name": "DDDDD", "Children": [ { "ID": 9, "Name": "Hhhhh", "Children": [] } ] }, { "ID": 6, "Name": "Eeeee", "Children": [ { "ID": 7, "Name": "FFFF", "Children": [] }, { "id": 10, "Name": "JJJJ", "Children": [] } ] } ] }]
As the parent node with ID 8 is ID 3, and the parent node with ID 3 is 1, but the parent node is not currently present, so ID 3 is the top node. The same is true of others;
The JS code is as follows:
//Property configuration SettingsLet attr ={ID:' ID ', Parendid:' Parendid ', Name:' Name ', Rootid:1};functiontotreedata (data, attr) {Let tree= []; Let Resdata=data; for(Let i = 0; i < resdata.length; i++) { if(Resdata[i].parendid = = =attr.rootid) {Let obj={id:resdata[i][attr.id], name:resdata[i][attr.name], children: []}; Tree.push (obj); Resdata.splice (i,1); I--; } } varRun =function(treearrs) {if(Resdata.length > 0) { for(Let i = 0; i < treearrs.length; i++) { for(Let j = 0; J < Resdata.length; J + +) { if(Treearrs[i].id = = =Resdata[j][attr.parendid]) {Let obj={id:resdata[j][attr.id], name:resdata[j][attr.name], children: [] }; Treearrs[i].children.push (obj); Resdata.splice (J,1); J--; }} run (Treearrs[i].children); } } }; Run (tree); returnTree;} Let arr=Totreedata (Alldatas, attr); Console.log (arr);
JS converts data with parent-child relationships into tree-structured data