Saturday, October 18, 2025
HomeLanguagesJavascriptCollect.js keyBy() Method

Collect.js keyBy() Method

The keyBy() method is used to keys the collection elements by the given key. If the collection contains multiple items with same key then the last element will appear.

Syntax:

collect(array).keyBy(key)

Parameters: The collect() method takes one argument that is converted into the collection and then keyBy() method is applied on it. The keyBy() method holds the key value.

Return Value: This method returns the collection elements by given key value.

Below example illustrate the keyBy() method in collect.js:

Example 1:

Javascript




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


Output:

{
  Rahul: { name: 'Rahul', score: 98 },
  Aditya: { name: 'Aditya', score: 96 },
  Abhishek: { name: 'Abhishek', score: 80 }
}

Example 2:

Javascript




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 key_val = collection.keyBy('dob');
  
console.log(key_val.all());


Output:

{
  '25-10-96': { 
    name: 'Aditya', dob: '25-10-96', 
    section: 'B', score: 96 
  },
  '16-08-94': { 
    name: 'Abhishek', dob: '16-08-94', 
    section: 'A', score: 80 
  },
  '19-08-96': { 
    name: 'Rahul', dob: '19-08-96', 
    section: 'B', score: 77 
  }
}
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS