“Offer comes, ask friends to take it! I am participating in the 2022 Spring Recruit Punch card campaign. Click here for more details.”
I. Title Description:
In the project, it was necessary to display the tree structure according to the data returned by the background. Because it was text extraction, the background could only return the number of the current directory, so it was necessary to determine the corresponding hierarchy according to the directory number, and then convert it into a tree structure
The data structure is as follows:
Const listData = [{txtId: '1', label: 'level 1'}, {txtId: '1.1', label: 'level of 1.1'}, {txtId: '1.1.1, label: 'primary 1.1.1'}, {txtId: '1.1.2, label:' primary 1.1.2}, {txtId: '1.1.3, label:' primary 1.1.3}, {txtId: '1.2.1, label: 'primary 1.2.1'}, {txtId: '1.2.2, label:' primary 1.2.2}, {txtId: "1.2.3" label: 'primary 1.2.3'}, {txtId: '1.3', the label: 'level of 1.3'}, {txtId: '1.4', label: 'level of 1.4'}, {txtId: 'the 1.4.1, label:' primary 1.4.1}];Copy the code
The page display
Ii. Analysis of Ideas:
- First determine the root node
- So the first loop, we get txtId, and according to txtId, we cut it into an array using the spit method in String
- Loop, check whether result exists, if not, create children, if exists, add to children
Iii. AC Code:
Function pos(list, id) {let _pos = -1; list.map((d, i) => { if (d.id === id) { _pos = i; }}); return _pos; } function listStrToTree(data) { const result = []; data.map((d) => { const child = d.txtId.split('.'); let temp = result; child.map((d2) => { const _pos = pos(temp, d2); if( _pos ! == -1 ){ temp = temp[_pos]['children']; } else { temp.push({ id: d2, txtId: d.txtId, label: d.label, children: [] }); temp = temp[temp.length - 1]['children']; }}); }); return result; }Copy the code
Iv. Summary:
Id is to confirm whether it exists in the current txtId cut array, in the whole tree data, still need a unique ID, so you can use txtId as the key binding unique ID;