535 字
3 分钟
最新主流浏览器已经支持Object.groupBy()和Map.groupBy()
当处理数组数据时,有时我们需要根据特定的字段或条件对数据进行分组。在过去,实现数组分组需要编写自定义的逻辑来迭代数组、创建分组并将对象添加到正确的组中。这种方式可能会导致冗长且容易出错的代码。然而,幸运的是,JavaScript 引入了内置方法 Object.groupBy()
和 Map.groupBy()
,并且得到各大主流浏览器的支持。这两个方法在最新版本 Firefox 119 和 Chrome 119 都已经得到支持。接下来我们来看看如何使用。
Object.groupBy()
Object.groupBy()
用于分组名称是字符串或Symbol
类型的值时,也就是回调函数返回一个字符串或Symbol
作为分组的键。如给到如下数据要求用type
值进行分组:
const inventory = [ { name: 'asparagus', type: 'vegetables', quantity: 5 }, { name: 'bananas', type: 'fruit', quantity: 0 }, { name: 'goat', type: 'meat', quantity: 23 }, { name: 'cherries', type: 'fruit', quantity: 5 }, { name: 'fish', type: 'meat', quantity: 22 }, ]
在过去,你可能会使用数组的reduce
方法来实现这个功能,如下所示:
const groupedInventory = inventory.reduce((acc, item) => { const { type, ...rest } = item if (!acc[type]) { acc[type] = [] } acc[type].push(rest) return acc }, {})
而使用Object.groupBy()
方法会简单很多。
const groupedInventory = Object.groupBy(inventory, ({ type }) => type) /** 结果如下: { vegetables: [{ name: 'asparagus', type: 'vegetables', quantity: 5 }], fruit: [ { name: 'bananas', type: 'fruit', quantity: 0 }, { name: 'cherries', type: 'fruit', quantity: 5 }, ], meat: [ { name: 'goat', type: 'meat', quantity: 23 }, { name: 'fish', type: 'meat', quantity: 22 }, ], } */
Map.groupBy()
Map
类型数据的键值可以是任意数据类型,也就是回调函数返回的值可以是任意数据类型。还是使用前面的数据,以quantity
是否小于 6 进行分组。
const restock = { restock: true } const sufficient = { restock: false } const result = Map.groupBy(inventory, ({ quantity }) => (quantity < 6 ? restock : sufficient)) console.log(result.get(restock)) /** 结果如下: [ { name: 'asparagus', type: 'vegetables', quantity: 5 }, { name: 'bananas', type: 'fruit', quantity: 0 }, { name: 'cherries', type: 'fruit', quantity: 5 }, ] */
上面的代码使用了两个对象作为键值,并得到了一个包含这两个对象作为键值的Map
数据。
最新主流浏览器已经支持Object.groupBy()和Map.groupBy()
https://fuwari.vercel.app/posts/20231106/