Open In App

Collect.js mapToDictionary() Method

Last Updated : 26 Nov, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

The mapToDictionary() method is used to run a dictionary map over the collection items. The given callback function returns an associative array with a single (key, value) pair.

Syntax:

collect(array).mapToDictionary(callback)

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

Return Value: This method returns an associative array with a single (key, value) pair.

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

Example 1:

Javascript




const collect = require('collect.js');
  
let obj = [{
    name: 'Ashok',
    score: 75
},
{
    name: 'Rakesh',
    score: 86
},
{
    name: 'Rajesh',
    score: 56
}];
  
const collection = collect(obj);
  
const sequence = collection.mapToDictionary(
    element => [element.name, element.score]);
  
console.log(sequence.all());


Output:

{ Ashok: [ 75 ], Rakesh: [ 86 ], Rajesh: [ 56 ] }

Example 2:

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: '19-08-96',
    },
];
  
const collection = collect(obj);
  
const sequence = collection.mapToDictionary(
    element => [element.name, element.dob]);
  
console.log(sequence.all());


Output:

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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads