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
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' ,
},
];
const collection = collect(obj);
const sequence = collection.mapWithKeys(
element => [element.name, element.dob]);
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
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
}
];
const collection = collect(obj);
const sequence = collection.mapWithKeys(
element => [element.name, element.section]);
console.log(sequence.all());
|
Run the index.js file using the following command:
node index.js
Output:
{ Rahul: 'A', Aditya: 'B', Abhishek: 'A' }
Last Updated :
19 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...