12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- let testData = [
- {
- groupId: 1,
- name: 1,
- parentId: ''
- },
- {
- groupId: 2,
- name: 2,
- parentId: ''
- },{
- groupId: 3,
- name: 3,
- parentId: ''
- },{
- groupId: 4,
- name: 1.4,
- parentId: 1
- },
- {
- groupId: 5,
- name: 1.5,
- parentId: 1
- },
- {
- groupId: 6,
- name: 1.6,
- parentId: 1
- },
- {
- groupId: 7,
- name: 6.7,
- parentId: 6
- },
- {
- groupId: 8,
- name: 6.8,
- parentId: 6
- },
- {
- groupId: 9,
- name: 2.9,
- parentId: 2
- },
- {
- groupId: 10,
- name: 2.10,
- parentId: 2
- }
- ];
- function arrayToTree(array,oneLevelId='',fieldKey,parentKey){
- // 数组转tree
- function loop(_arr,parentId){
- return _arr.reduce((acc,cur,ind,arr)=>{
- if(cur[parentKey] === parentId){
- acc.push(cur);
- cur.children = loop(arr,cur['fieldKey']);
- }
- return acc;
- },[]);
- }
- return loop(array,oneLevelId);
- }
- function test(){
- arrayToTree(testData);// array [{…}, {…}, {…}]
- }
|