我们可以使用JavaScript的Array.reduce()方法来按关键字对对象数组进行分组。该方法将一个回调函数作为参数,该函数接受累加器和当前元素作为参数,并返回累加器的值。在此过程中,我们可以创建一个新的对象,将每个关键字作为属性并存储相应的对象数组。
代码示例:
const arr = [
{ name: "apple", type: "fruit" },
{ name: "pear", type: "fruit" },
{ name: "carrot", type: "vegetable" },
{ name: "broccoli", type: "vegetable" },
{ name: "banana", type: "fruit" },
];
const groupBy = (arr, key) =>
arr.reduce((acc, obj) => {
const property = obj[key];
acc[property] = acc[property] || [];
acc[property].push(obj);
return acc;
}, {});
const result = groupBy(arr, "type");
console.log(result);
/* Output:
{
fruit: [
{ name: 'apple', type: 'fruit' },
{ name: 'pear', type: 'fruit' },
{ name: 'banana', type: 'fruit' }
],
vegetable: [
{ name: 'carrot', type: 'vegetable' },
{ name: 'broccoli', type: 'vegetable' }
]
}
*/
在上面的示例中,我们首先定义了一个对象数组,该数组具有名称和类型属性。接下来,我们定义了一个名为“groupBy”的函数,该函数接受一个数组和一个关键字作为参数,并使用reduce()方法生成已分组的对象。最后,我们调用函数,并传递数组和关键字作为参数,并将结果存储在变量“result”中。输出结果为按类型分组的对象数组。
下一篇:按关键字对一组数据进行排序