const obj = [
{
"groupingType": "1",
"remark": "梨花带雨",
"totalRmbMoney": 7,
"kyeGroupingType": "广州一组"
},
{
"groupingType": "2",
"remark": "99",
"totalRmbMoney": 0,
"kyeGroupingType": "广州二组"
},
{
"groupingType": "2",
"remark": "重生之我百亿富豪",
"totalRmbMoney": 66,
"kyeGroupingType": "广州二组"
},
{
"groupingType": "2",
"remark": "1",
"totalRmbMoney": 99,
"kyeGroupingType": "广州二组"
},
{
"groupingType": "3",
"remark": "哈韩",
"totalRmbMoney": 12,
"kyeGroupingType": "佛山一组"
},
{
"groupingType": "3",
"remark": "大表姐",
"totalRmbMoney": 0,
"kyeGroupingType": "佛山一组"
},
{
"groupingType": "3",
"remark": "梨花带雨",
"totalRmbMoney": 0,
"kyeGroupingType": "佛山一组"
},
{
"groupingType": "4",
"remark": "666",
"totalRmbMoney": 0,
"kyeGroupingType": "广州一组"
},
{
"groupingType": "4",
"remark": "佛山一个",
"totalRmbMoney": 0,
"kyeGroupingType": "广州一组"
},
{
"groupingType": "4",
"remark": "大表哥",
"totalRmbMoney": 78,
"jobType": "1",
"kyeGroupingType": "广州一组"
}
]
const groupBy = (array: any, key: any) => {
return array.reduce((result: any, currentItem: any) => {
// 使用 key 函数如果有定义,否则直接获取属性值
const groupKey = typeof key === 'function' ? key(currentItem) : currentItem[key];
// 初始化分类数组
if (!result[groupKey]) {
result[groupKey] = [];
}
// 将当前项推入分类数组
result[groupKey].push(currentItem);
return result;
}, {});
};
const newobj = groupBy(obj, 'kyeGroupingType')
console.log('newobj', newobj)
输出结果如图: