例如↓数组中每条数据的url字段相似
arr = [{id:0,dir:'/edit/aaaa/bbbb/cccc/dddd/20231123',title:'第一条数据'},{id:1,dir:'/edit/aaaa/bbbb/cccc/dddd/20241011',title:'第二条数据'},{id:2,dir:'/edit/aaaa/bbbb/cccc/dddd/20240623',title:'第三条数据'},{id:3,dir:'/edit/aaaa/bbbb/cccc/dddd/20240313',title:'第四条数据'},{id:4,dir:'/edit/aaaa/bbbb/cccc/dddd/20241224/12',title:'第五条数据'},
]
变成↓
arr = [{id:0,dir:'/edit/aaaa/bbbb/cccc/dddd/20231123',title:'第一条数据',children:[{id:1,dir:'/edit/aaaa/bbbb/cccc/dddd/20241011',title:'第二条数据'},{id:2,dir:'/edit/aaaa/bbbb/cccc/dddd/20240623',title:'第三条数据'},{id:3,dir:'/edit/aaaa/bbbb/cccc/dddd/20240313',title:'第四条数据'},{id:4,dir:'/edit/aaaa/bbbb/cccc/dddd/20241224/12',title:'第五条数据'}]} ]
实现方法
unique5(data) {var result = []; var hash = {};let sum;for (var i = 0; i < data.length; i++) {//截取出来相似的部分 (/edit/aaaa/bbbb/ccc/ddd)if ((data[i].dir.slice(data[i].dir.lastIndexOf('/')) +'').length=== 9) { //判断是否为时间sum = data[i].dir.slice(0, data[i].dir.lastIndexOf('/')); } else { //例如第五条数据特殊数据判断const lastIndex = data[i].dir.lastIndexOf('/');sum = data[i].dir.slice(0, data[i].dir.lastIndexOf('/', lastIndex - 1));}if (!hash[sum]) {//不存在加进去 result.push({...data[i], children: []});hash[sum] = true;} else { // 已存在 加入 children 里面const dindData = result.find(item => {return item.dir.includes(sum);});dindData ? dindData.children.push({...data[i]}) : null;}}return result;},