Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptCollect.js mapWithKeys() Method

Collect.js mapWithKeys() Method

The mapWithKeys() method is used to iterate through the collection elements and passes each collection element into the given callback function. The callback function returns an array that contains the key, value pair.

Syntax:

collect(array).mapWithKeys(callback)

Parameters: The collect() method takes one argument that is converted into the collection and then mapWithKeys() method is applied to it. The mapWithKeys() method holds the callback function as a parameter.

Return Value: This method returns an array that contains the key, value pair.

Module Installation: Install collect.js module using the following command from the root directory of your project:

npm install collect.js

The below example illustrates the mapWithKeys() method in collect.js:

Example 1: Filename: index.js

Javascript




// Requiring the module
const collect = require('collect.js');
 
let obj = [
    {
        name: 'Rahul',
        dob: '25-10-96',
    },
    {
        name: 'Aditya',
        dob: '25-10-96',
    },
    {
        name: 'Abhishek',
        dob: '16-08-94',
    },
    {
        name: 'Rahul',
        dob: '25-10-96',
    },
];
 
// Creating collection object
const collection = collect(obj);
 
// Function call
const sequence = collection.mapWithKeys(
    element => [element.name, element.dob]);
 
// Printing the sequence
console.log(sequence.all());


 
 

Run the index.js file using the following command:

node index.js

Output: 

{ Rahul: '25-10-96', Aditya: '25-10-96', Abhishek: '16-08-94' }

Example 2: Filename: index.js

Javascript




// Requiring the module
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
    }
];
 
// Creating collection object
const collection = collect(obj);
 
// Function call
const sequence = collection.mapWithKeys(
    element => [element.name, element.section]);
 
// Printing the sequence
console.log(sequence.all());


 
 

Run the index.js file using the following command:

node index.js

 Output:

{ Rahul: 'A', Aditya: 'B', Abhishek: 'A' }

 

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

Recent Comments