【发布时间】:2022-08-11 15:58:46
【问题描述】:
我试图了解.reduce() 函数以及执行以下操作的最佳方法。
我有以下代码:
const products = [
{ name: \'apples\', category: \'fruits\' },
{ name: \'oranges\', category: \'fruits\' },
{ name: \'potatoes\', category: \'vegetables\' }
];
const groupByCategory = products.reduce((group, product) => {
const { category } = product;
group[category] = group[category] ?? [];
group[category].push(product);
return group;
}, {});
我想添加一个没有 \'category\' 属性的产品,并且我希望它被推送到一个特定的键中,而不是被分组到 \"undefined\" 中,所以我将它编辑为:
const products = [
{ name: \"apples\", category: \"fruits\" },
{ name: \"oranges\", category: \"fruits\" },
{ name: \"potatoes\", category: \"vegetables\" },
{ name: \"guava\"}
];
const groupByCategory = products.reduce((group, product) => {
const { category } = product ;
// check if \'category\' exists, if it doesn\'t store it as an empty array to push to
group[category] = group[category] ?? [];
// if category is undefined, push it into \'nocategory\'. Otherwise push into relevant.
if(!category){
group[\'nocategory\'].push(product);
} else {
group[category].push(product);
};
return group;
}, {\'nocategory\':[]});
console.log(JSON.stringify(groupByCategory, null, 2));
在大多数情况下,它可以工作(仍然有一个“未定义”组,但至少该对象被推入正确的组)。
我确信有更好的解决方案/正确的方法来做到这一点。任何指针将不胜感激。
标签: javascript reduce simplify