有人知道一种方法(lodash如果可能的话)通过对象键分组对象数组,然后根据分组创建一个新的对象数组吗?例如,我有一个汽车对象数组:
const cars = [
{
'make': 'audi',
'model': 'r8',
'year': '2012'
}, {
'make': 'audi',
'model': 'rs5',
'year': '2013'
}, {
'make': 'ford',
'model': 'mustang',
'year': '2012'
}, {
'make': 'ford',
'model': 'fusion',
'year': '2015'
}, {
'make': 'kia',
'model': 'optima',
'year': '2012'
},
];
我想创建一个新的汽车对象数组,由make分组:
const cars = {
'audi': [
{
'model': 'r8',
'year': '2012'
}, {
'model': 'rs5',
'year': '2013'
},
],
'ford': [
{
'model': 'mustang',
'year': '2012'
}, {
'model': 'fusion',
'year': '2015'
}
],
'kia': [
{
'model': 'optima',
'year': '2012'
}
]
}
@metakungfu answer略有不同,主要区别在于它从结果对象中省略了原始键,因为在某些情况下对象本身不再需要它,因为它现在在父对象中可用。
const groupBy = (_k, a) => a.reduce((r, {[_k]:k, ...p}) => ({
...r, ...{[k]: (
r[k] ? [...r[k], {...p}] : [{...p}]
)}
}), {});
考虑到您的原始输入对象:
console.log(groupBy('make', cars));
会导致:
{
audi: [
{ model: 'r8', year: '2012' },
{ model: 'rs5', year: '2013' }
],
ford: [
{ model: 'mustang', year: '2012' },
{ model: 'fusion', year: '2015' }
],
kia: [
{ model: 'optima', year: '2012' }
]
}
const reGroup = (list, key) => {
const newGroup = {};
list.forEach(item => {
const newItem = Object.assign({}, item);
delete newItem[key];
newGroup[item[key]] = newGroup[item[key]] || [];
newGroup[item[key]].push(newItem);
});
return newGroup;
};
const animals = [
{
type: 'dog',
breed: 'puddle'
},
{
type: 'dog',
breed: 'labradoodle'
},
{
type: 'cat',
breed: 'siamese'
},
{
type: 'dog',
breed: 'french bulldog'
},
{
type: 'cat',
breed: 'mud'
}
];
console.log(reGroup(animals, 'type'));
const cars = [
{
'make': 'audi',
'model': 'r8',
'year': '2012'
}, {
'make': 'audi',
'model': 'rs5',
'year': '2013'
}, {
'make': 'ford',
'model': 'mustang',
'year': '2012'
}, {
'make': 'ford',
'model': 'fusion',
'year': '2015'
}, {
'make': 'kia',
'model': 'optima',
'year': '2012'
},
];
console.log(reGroup(cars, 'make'));
这是一个通用函数,将返回Array groupBy自己的键。
const getSectionListGroupedByKey = < T > (
property: keyof T,
List: Array < T >
): Array < {
title: T[keyof T];data: Array < T >
} > => {
const sectionList: Array < {
title: T[keyof T];data: Array < T >
} > = [];
if (!property || !List ? .[0] ? .[property]) {
return [];
}
const groupedTxnListMap: Map < T[keyof T], Array < T >> = List.reduce((acc, cv) => {
const keyValue: T[keyof T] = cv[property];
if (acc.has(keyValue)) {
acc.get(keyValue) ? .push(cv);
} else {
acc.set(keyValue, [cv]);
}
return acc;
}, new Map < T[keyof T], Array < T >> ());
groupedTxnListMap.forEach((value, key) => {
sectionList.push({
title: key,
data: value
});
});
return sectionList;
};
// Example
const cars = [{
'make': 'audi',
'model': 'r8',
'year': '2012'
}, {
'make': 'audi',
'model': 'rs5',
'year': '2013'
}, {
'make': 'ford',
'model': 'mustang',
'year': '2012'
}, {
'make': 'ford',
'model': 'fusion',
'year': '2015'
}, {
'make': 'kia',
'model': 'optima',
'year': '2012'
}, ];
const result = getSectionListGroupedByKey('make', cars);
console.log('result: ', result)