原始数据如下:
list:[
{name: "手持式红外线测温仪",name_id: "21",type: "医疗设备",type_id: "104"},
{name: "手持式红外线测温仪",name_id: "21",type: "医疗设备",type_id: "104"},
{name: "手持式红外线测温仪",name_id: "21",type: "医疗设备1",type_id: "105"},
{name: "手持式红外线测温仪",name_id: "21",type: "医疗设备",type_id: "104"},
{name: "手持式红外线测温仪",name_id: "21",type: "医疗设备1",type_id: "105"},
{name: "手持式红外线测温仪",name_id: "21",type: "医疗设备",type_id: "104"}
]
按照type进行分组,想要得到如下数据:
typelist:[
{
type:"医疗设备",
data:[
{name: "手持式红外线测温仪",name_id: "21",type: "医疗设备",type_id: "104"},
{name: "手持式红外线测温仪",name_id: "21",type: "医疗设备",type_id: "104"},
{name: "手持式红外线测温仪",name_id: "21",type: "医疗设备",type_id: "104"},
{name: "手持式红外线测温仪",name_id: "21",type: "医疗设备",type_id: "104"}
]
},
{
type:"医疗设备1",
data:[
{name: "手持式红外线测温仪",name_id: "21",type: "医疗设备1",type_id: "105"},
{name: "手持式红外线测温仪",name_id: "21",type: "医疗设备1",type_id: "105"}
]
}
]
代码实现:
arrayGroupBy(list, groupId){
function groupBy(array, f){
const groups = {}
array.forEach(function (o) {
const group = JSON.stringify(f(o))
groups[group] = groups[group] || []
groups[group].push(o)
})
return groups;
};
return groupBy(list, function (item) {
return item[groupId]
});
},
let json = this.arrayGroupBy(this.list,"type")
let {keys,values,entries} = Object
for (const [key,val] of entries(json)) {
let reg = new RegExp('"',"g");
let newKey = key.replace(reg, "");
this.typelist.push({
type:newKey,
data:val
})
}