📜  Collect.js groupBy() 方法

📅  最后修改于: 2022-05-13 01:56:36.736000             🧑  作者: Mango

Collect.js groupBy() 方法

Collect.js是一个用于处理数组和对象的包装库,它无依赖且易于使用。 groupBy()方法用于通过给定的键将给定的集合项分组为多个集合

句法:

collect(array).groupBy(key)

参数: collect()方法采用一个参数,该参数转换为集合,然后对其应用groupBy()方法。 groupBy()方法保存对象的键。

返回值:此方法返回按给定键分组的多个集合。

示例 1:下面的示例说明了collect.js中的groupBy()方法

html
const collect = require('collect.js');
   
let obj = [
    {
        name: 'Rahul',
        score: 98,
    },
    {
        name: 'Aditya',
        score: 96,
    },
    {
        name: 'Abhishek',
        score: 80
    }
];
   
const collection = collect(obj); 
const grouped_val = collection.groupBy('name'); 
console.log(grouped_val.all());


html
const collect = require('collect.js');
   
let obj = [
    {
        name: 'Rahul',
        dob: '25-10-96',
        section: 'A',
        score: 98,
    },
    {
        name: 'Aditya',
        dob: '25-10-96',
        section: 'B',
        score: 96,
    },
    {
        name: 'Abhishek',
        dob: '16-08-94',
        section: 'A',
        score: 80
    },
    {
        name: 'Rahul',
        dob: '19-08-96',
        section: 'B',
        score: 77,
    },
];
   
const collection = collect(obj); 
const grouped_val = collection.groupBy('dob'); 
console.log(grouped_val.all());


输出:

{
  Rahul: Collection { items: [ [Object] ] }, 
  Aditya: Collection { items: [ [Object] ] },
  Abhishek: Collection { items: [ [Object] ] }
}

示例 2:

html

const collect = require('collect.js');
   
let obj = [
    {
        name: 'Rahul',
        dob: '25-10-96',
        section: 'A',
        score: 98,
    },
    {
        name: 'Aditya',
        dob: '25-10-96',
        section: 'B',
        score: 96,
    },
    {
        name: 'Abhishek',
        dob: '16-08-94',
        section: 'A',
        score: 80
    },
    {
        name: 'Rahul',
        dob: '19-08-96',
        section: 'B',
        score: 77,
    },
];
   
const collection = collect(obj); 
const grouped_val = collection.groupBy('dob'); 
console.log(grouped_val.all());

输出:

{
  '25-10-96': Collection { items: [ [Object], [Object] ] },
  '16-08-94': Collection { items: [ [Object] ] },
  '19-08-96': Collection { items: [ [Object] ] }
}