【问题标题】:Javascript .reduce() tips? Is there a way to rename 'undefined' group?Javascript .reduce() 提示?有没有办法重命名 \'undefined\' 组?
【发布时间】: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


    【解决方案1】:

    你在这里创建未定义

    group[category] = group[category] ?? []; // category can be undefined
    

    将创建移到 if-else 语句中

    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
      // removed
      
      // if category is undefined, push it into 'nocategory'. Otherwise push into relevant.
      if(!category){
         group['nocategory'].push(product);
      } else {
        group[category] = group[category] ?? [] // HERE
        group[category].push(product);
      };
      return group;
    }, {'nocategory':[]});
    
    console.log(JSON.stringify(groupByCategory, null, 2));

    【讨论】:

      猜你喜欢
      • 2011-03-26
      • 2017-12-08
      • 1970-01-01
      • 1970-01-01
      • 2021-10-26
      • 2011-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多