ES6中如何用Object.groupBy分组对象数组

es6没有Object.groupby方法,但可用reduce模拟实现。1. 使用reduce遍历数组,根据字符串或函数形式的key进行分组;2. 若分组字段缺失,默认值设为’unknown’;3. 也可用for…of循环map提升性能;4. 对于复杂逻辑,可通过函数定义分组规则。例如按年龄段将用户分为’20s’、’30s’等组别。

ES6中如何用Object.groupBy分组对象数组

ES6 本身并没有 Object.groupBy 方法,所以不能直接用。但我们可以用 reduce 来模拟实现类似的功能,或者使用一些第三方库。

ES6中如何用Object.groupBy分组对象数组

解决方案

直接上代码,先看怎么用 reduce 实现:

function groupBy(list, key) {   return list.reduce((accumulator, currentValue) => {     const groupKey = typeof key === 'function' ? key(currentValue) : currentValue[key];     if (!accumulator[groupKey]) {       accumulator[groupKey] = [];     }     accumulator[groupKey].push(currentValue);     return accumulator;   }, {}); }  // 示例 const people = [   { name: 'Alice', age: 25, city: 'New York' },   { name: 'Bob', age: 30, city: 'Los Angeles' },   { name: 'Charlie', age: 25, city: 'Chicago' } ];  const groupedByAge = groupBy(people, 'age'); console.log(groupedByAge); // 输出: // { //   25: [ //     { name: 'Alice', age: 25, city: 'New York' }, //     { name: 'Charlie', age: 25, city: 'Chicago' } //   ], //   30: [ //     { name: 'Bob', age: 30, city: 'Los Angeles' } //   ] // }  const groupedByCity = groupBy(people, person => person.city.substring(0,3)); console.log(groupedByCity); // 输出: // { //   "New": [ //     { name: 'Alice', age: 25, city: 'New York' } //   ], //   "Los": [ //     { name: 'Bob', age: 30, city: 'Los Angeles' } //   ], //   "Chi": [ //     { name: 'Charlie', age: 25, city: 'Chicago' } //   ] // } 

这段代码的核心在于 reduce 函数。它遍历数组,并根据指定的 key(可以是字符串或函数)将元素放入不同的组。 如果 accumulator 中没有对应的 key,就初始化一个空数组。

ES6中如何用Object.groupBy分组对象数组

如何处理分组字段缺失的情况?

如果你的对象数组中,某些对象缺少分组依据的字段,直接访问可能会导致错误。可以增加一个判断,如果字段不存在,则赋予一个默认值,例如 “unknown”。

function groupBy(list, key) {   return list.reduce((accumulator, currentValue) => {     const groupKey = typeof key === 'function' ? key(currentValue) : currentValue[key] || 'unknown'; // 增加默认值     if (!accumulator[groupKey]) {       accumulator[groupKey] = [];     }     accumulator[groupKey].push(currentValue);     return accumulator;   }, {}); }  const products = [   { name: 'Laptop', category: 'Electronics' },   { name: 'T-shirt' },   { name: 'Headphones', category: 'Electronics' } ];  const groupedByCategory = groupBy(products, 'category'); console.log(groupedByCategory); // 输出: // { //   Electronics: [ //     { name: 'Laptop', category: 'Electronics' }, //     { name: 'Headphones', category: 'Electronics' } //   ], //   unknown: [ //     { name: 'T-shirt' } //   ] // }

除了 reduce 还有其他方法吗?

当然,除了 reduce,还可以使用 for…of 循环来实现,虽然代码会稍微多一点,但可读性可能会更好。

ES6中如何用Object.groupBy分组对象数组

function groupBy(list, key) {   const result = {};   for (const item of list) {     const groupKey = typeof key === 'function' ? key(item) : item[key];     if (!result[groupKey]) {       result[groupKey] = [];     }     result[groupKey].push(item);   }   return result; }

甚至,如果对性能有极致要求,可以考虑使用 Map 代替普通对象,因为 Map 在某些情况下性能更好。

如何处理更复杂的分组逻辑?

有时候,分组的逻辑可能不仅仅是简单的属性值相等,可能需要进行一些计算或转换。 这时候,可以将分组的 key 定义为一个函数,并在函数中实现复杂的逻辑。 比如,根据用户的年龄段进行分组:

const users = [   { name: 'Alice', age: 25 },   { name: 'Bob', age: 35 },   { name: 'Charlie', age: 45 },   { name: 'David', age: 55 } ];  const groupedByAgeRange = groupBy(users, user => {   if (user.age < 30) {     return '20s';   } else if (user.age < 40) {     return '30s';   } else if (user.age < 50) {     return '40s';   } else {     return '50+';   } });  console.log(groupedByAgeRange); // 输出: // { //   '20s': [ { name: 'Alice', age: 25 } ], //   '30s': [ { name: 'Bob', age: 35 } ], //   '40s': [ { name: 'Charlie', age: 45 } ], //   '50+': [ { name: 'David', age: 55 } ] // }

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享