Tuesday, December 31, 2024
Google search engine
HomeLanguagesJavascriptCollect.js mapInto() Method

Collect.js mapInto() Method

The mapInto() method is used to iterate through the collection elements and instantiate the given class with each element as a constructor.

Syntax:

collect(array).mapInto()

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

Return Value: This method returns the mapped collection elements.

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

Example 1:

Javascript




const collect = require('collect.js');
  
const data = function (name) {
    this.name = name;
};
  
const arr = ['GFG', 'Geeks', 'neveropen'];
  
const collection = collect(arr);
  
const elements = collection.mapInto(data);
  
console.log(elements.all());


Output:

[
  data { name: 'GFG' },
  data { name: 'Geeks' },
  data { name: 'neveropen' }
]

Example 2:

Javascript




const collect = require('collect.js');
  
const data = function (name, dob) {
    this.name = name;
    this.dob = dob;
};
  
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 objects = collection.mapInto(data);
  
console.log(objects.all());


Output:

[
  data {
    name: { 
      name: 'Rahul', 
      dob: '25-10-96', 
      section: 'A', 
      score: 98 
    },
    dob: 0
  },
  data {
    name: { 
      name: 'Aditya', 
      dob: '25-10-96', 
      section: 'B', 
      score: 96 },
    dob: 1
  },
  data {
    name: { 
      name: 'Abhishek', 
      dob: '16-08-94', 
      section: 'A', 
      score: 80 
    },
    dob: 2
  },
  data {
    name: { 
      name: 'Rahul', 
      dob: '19-08-96', 
      section: 'B', 
      score: 77 
    },
    dob: 3
  }
]

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