Vue实战(十):对数组数据的拆分和分组合并
数据初始化
js
//第一种情况
tableData: [
{ id: 1, name: ["A", "B"] },
{ id: 2, name: ["A", "C"] },
{ id: 3, name: ["B", "C"] },
{ id: 4, name: ["A", "B", "C"] },
],
//第二种情况
tableData1: [
{ id: 1, name: ["A"] },
{ id: 2, name: ["B"] },
{ id: 3, name: ["C"] },
],
//第三种情况
tableData2: [
{ id: 1, name: ["A"] },
{ id: 2, name: ["A"] },
{ id: 3, name: ["C"] },
],
分解数据
js
separateData(arr) {
let newArr = [];
arr.forEach((item) => {
item.name.forEach((it) => {
var obj = {};
this.$set(obj, "id", item.id);
this.$set(obj, "name", it.split(","));
newArr.splice(newArr.length, 0, obj);
});
});
return newArr;
}
分组数据
js
groupBy(objectArray, property) {
return objectArray.reduce(function (acc, obj) {
var key = obj[property];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(obj);
return acc;
}, {});
}
第一种情况测试
js
console.log(JSON.stringify(this.tableData));
let arr = this.separateData(this.tableData);
console.log(JSON.stringify(arr));
let result = this.groupBy(arr, "name");
console.log(JSON.stringify(result));
第二种情况测试
js
console.log(JSON.stringify(this.tableData1));
let arr = this.separateData(this.tableData1);
console.log(JSON.stringify(arr));
let result = this.groupBy(arr, "name");
console.log(JSON.stringify(result));
第三种情况测试
js
console.log(JSON.stringify(this.tableData2));
let arr = this.separateData(this.tableData2);
console.log(JSON.stringify(arr));
let result = this.groupBy(arr, "name");
console.log(JSON.stringify(result));