项目中成员列表需要按成员类型来显示,但是后台返回的列表数据格式不是我们遍历所需要的格式。
先把数据分组:
const agentList = [
{
"work_name": "张三",
"agent_title": "店长"
},
{
"work_name": "李四",
"agent_title": "销售"
},
{
"work_name": "小宝",
"agent_title": "销售"
},
{
"work_name": "刘怀",
"agent_title": "顾问"
},
{
"work_name": "李三",
"agent_title": "顾问"
}
];
let group = agentList.reduce((pre, item) => {
pre[item.agent_title] = [...pre[item.agent_title] || [], item];
return pre;
}, {});
执行上面代码,得到一个分好组的对象

现在的数据格式还不能直接用于表格中遍历,所以还要再处理一下,把它变为一个数组
const finalGroups = Object.keys(groups).map(key=>{
const obj = {
name: key,
value: groups[key]
};
return obj;
});

综上,把这个过程封装为一个函数
/**
** @param array: 对象数组
** @param groupParam: 对象数组中对象的键名
** @return result:按键名分组过的对象数组
*/
function arrayGroupBy(array, groupParam) {
const arr = array;
const groupedArr = arr.reduce((pre, item) => {
const groupName = item[groupParam];
pre[groupName] = [...pre[groupName] || [], item];
return pre;
}, {});
const result = Object.keys(groupedArr).map(key=>{
const obj = {
name: key,
value: groupedArr[key]
};
return obj;
});
return result;
}
网友评论