需求很明了,首先我们来看原始数据
// 样例数据
const data= [
{
"id": null,
"projectId": "4513f7ec42f34a3eb41a40dafe8a35c8",
"companyId": "f2358250285c45f697dc46c2819fd93b",
"companyName": "ly公路施工单位1",
"companyType": "施工单位"
},
{
"id": null,
"projectId": "4513f7ec42f34a3eb41a40dafe8a35c8",
"companyId": "2553a6704af448df8e20445f7295b002",
"companyName": "ST公路施工单位",
"companyType": "施工单位"
},
{
"id": null,
"projectId": "4513f7ec42f34a3eb41a40dafe8a35c8",
"companyId": "b71e418e7c734788959282a220aff6fa",
"companyName": "公路测试单位jl01",
"companyType": "施工单位"
},
{
"id": null,
"projectId": "4513f7ec42f34a3eb41a40dafe8a35c8",
"companyId": "27c486e95fb94c5291fc42aee6110059",
"companyName": "公路测试单位jl02",
"companyType": "监理单位"
},
{
"id": null,
"projectId": "4513f7ec42f34a3eb41a40dafe8a35c8",
"companyId": "895eb0132c7742e58819058c560b83ff",
"companyName": "ly公路监理单位",
"companyType": "监理单位"
},
{
"id": null,
"projectId": "4513f7ec42f34a3eb41a40dafe8a35c8",
"companyId": "1f1d623eb3a24646866a76fc91a0b773",
"companyName": "ly公路设计单位",
"companyType": "设计单位"
},
{
"id": null,
"projectId": "4513f7ec42f34a3eb41a40dafe8a35c8",
"companyId": "e2ec515bb4204fde9d108e98a7e68bed",
"companyName": "刘强工地实验室",
"companyType": "检测单位"
}
]
预期结果输出
//处理表头过滤新的数据类型源
const filterType = (lists:[],type:string) =>{
const resType:any =[]; //获取所有类型 并做去重处理
if(lists.length){
tep.map(item=>{
resType.push(item[type])
})
}
return resType
}
//处理数据
const filterList = (lists:[],type:string) =>{
let Type = filterType(lists,type);
//利用reduce内置循序机制检查重复及个数情况
return Type.reduce(function(prev:any,next:any){
prev[next] = (prev[next] + 1) || 1;
return prev;
},{});
}
//接入数据组装最终结果
const setList =(lists:any,type:string,st:string,rt:string) =>{
let Obj = filterList(lists,type);
let current = [];
for(let k in Obj){
let obj = {
st: k,
rt:Obj[k]
}
current.push(obj) //结果组装
}
return current
}
//使用时 传入数据源 及需要过滤的类型,组装数据的字段 1,2;
setList(data,'companyType','name','cunt')
输出结果