项目中由于数据量不大,后台并未做处理,因此前端拿到返回的Table数据需要处理成树形数据再渲染到表格中
- 原始数据
const dataList=[
{
"id": 44,
"seedlingName": "测试2",
"seedlingType": "测试2",
"seedlingAge": 2,
},
{
"id": 47,
"seedlingName": "试",
"seedlingType": "1",
"seedlingAge": 1,
},
{
"id": 45,
"seedlingName": "试2",
"seedlingType": "2",
"seedlingAge": 2,
},
{
"id": 43,
"seedlingName": "试1",
"seedlingType": "12",
"seedlingAge": 12,
},
{
"id": 49,
"seedlingName": "试1",
"seedlingType": "1",
"seedlingAge": 222,
},
{
"id": 50,
"seedlingName": "试1",
"seedlingType": "试1",
"seedlingAge": 1,
},
{
"id": 46,
"seedlingName": "测试2",
"seedlingType": "测试3",
"seedlingAge": 3,
},
{
"id": 42,
"seedlingName": "测试2",
"seedlingType": "12",
"seedlingAge": 12,
}
]
- 处理之后的数据(这里是按照名称做的归类[seedlingName])
const dataList=[
{
"id": 44,
"seedlingName": "测试2",
"seedlingType": "测试2",
"seedlingAge": 2,
"children": [
{
"id": 46,
"seedlingName": "测试2",
"seedlingType": "测试3",
"seedlingAge": 3,
},
{
"id": 42,
"seedlingName": "测试2",
"seedlingType": "12",
"seedlingAge": 12,
}
]
},
{
"id": 47,
"seedlingName": "试",
"seedlingType": "1",
"seedlingAge": 1,
"children": []
},
{
"id": 45,
"seedlingName": "试2",
"seedlingType": "2",
"seedlingAge": 2,
"children": []
},
{
"id": 43,
"seedlingName": "试1",
"seedlingType": "12",
"seedlingAge": 12,
"children": [
{
"id": 49,
"seedlingName": "试1",
"seedlingType": "1",
"seedlingAge": 222,
},
{
"id": 50,
"seedlingName": "试1",
"seedlingType": "试1",
"seedlingAge": 3,
}
]
}
]
思路
备注:由于处理完之后会影响到原始数据,所以不能直接赋值,做一下数据的拷贝 _.cloneDeep()
1. 先用map结构记录
function arrayToMap(data) {
var map = {};
for (var i = 0; i < data.length; i++) {
let name = data[i].seedlingName;
if (name != undefined) {
if (map[name] == undefined) {
map[name] = [];
}
map[name].push(data[i]);
}
}
return map;
}
2. 把map转成数组
//把map转成数组
function mapToArray(data) {
let array = [];
for (let p in data) {
array.push(data[p]);
}
return array;
}
3. 循环之后取出每一个数组第一个元素作为根节点,后面的作为子级
function arrayToTree(array) {
// 取出第一个元素作为根节点
const root = array.shift();
if (array.length) {
root.children = array;
} else {
root.children = [];
}
return root;
}
4. 调用
const treeArr = mapToArray(arrayToMap(dataList)).map((item) => {
var tree = arrayToTree(item);
return tree;
});
console.log(treeArr)
5. 实现模糊查询
这里查询的字段(seedlingName/seedlingAge/seedlingType),其中seedlingAge是数字类型,所以我在查询的时候将数字类型转成了字符串类型,使用indexOf实现此功能,然后将查询到的数据在转成树形结构
const tableFilter=ref([])
const selectParams = reactive({
seedlingName: '',
seedlingType: '',
seedlingAge: '',
});
tableFilter.value = _.cloneDeep(dataList); //dataList原始数据
getFuzzyQuery(selectParams);
const getFuzzyQuery = (params) => {
const filterVal = tableFilter.value.filter((item) => {
if (
item.seedlingName.indexOf(params.seedlingName) !== -1 &&
item.seedlingType.indexOf(params.seedlingType) !== -1 &&
item.seedlingAge.toString().indexOf(params.seedlingAge) !== -1
) {
return item;
}
});
tableData.value = getDisposeData(filterVal); //getDisposeData是将上面的处理封装了
};
效果图:
原始数据展示的表格:
处理完之后展示的表格