NodeJS 类型错误:products.groupBy不是函数

ncecgwcz  于 2022-11-29  发布在  Node.js
关注(0)|答案(2)|浏览(142)

我阅读到JS最近引入了一个新的数组方法groupBy来操作这样的数组

const products = [
  { name: 'apples', category: 'fruits' },
  { name: 'oranges', category: 'fruits' },
  { name: 'potatoes', category: 'vegetables' }
];

该代码

const groupByCategory = products.groupBy(product => {
  return product.category;
});
console.log(groupByCategory)

应产生以下输出

// {
//   'fruits': [
//     { name: 'apples', category: 'fruits' }, 
//     { name: 'oranges', category: 'fruits' },
//   ],
//   'vegetables': [
//     { name: 'potatoes', category: 'vegetables' }
//   ]
// }

但是,我使用了node 18.7.0,但日志显示为TypeError: products.groupBy is not a function。我的问题是,此方法是否适用于任何节点版本?

请注意我不会使用reduce

7rtdyuoh

7rtdyuoh1#

由于您使用的功能处于测试状态,因此必须使用npm i core-js安装其依赖项,然后可以通过导入. ex来访问此功能

require("core-js/actual/array/group-by-to-map");
require("core-js/actual/array/group-by");

const products = [
  { name: "apples", category: "fruits" },
  { name: "oranges", category: "fruits" },
  { name: "potatoes", category: "vegetables" }
];

const groupByCategory = products.groupBy((product) => {
  return product.category;
});

const groupByCategoryMap = products.groupByToMap((product) => {
  return product.category;
});

console.log(groupByCategory);
console.log(groupByCategoryMap);

你可以在同一个例子中看到这一点,他们谈论它的使用Read Here,如果你看代码示例中给出的论坛,它需要导入和安装core-js Here

4xrmg8kj

4xrmg8kj2#

使用Javascript Reduce()方法创建“按类似SQL分组”

const products = [
              { name: 'apples', category: 'fruits' },
              { name: 'oranges', category: 'fruits' },
              { name: 'potatoes', category: 'vegetables' }
            ];

            var result = products.reduce((x, y) => {

                (x[y.category] = x[y.category] || []).push(y);

                return x;

            }, {});

            console.log(result);

            Output:  {fruits: Array(2), vegetables: Array(1)}

相关问题