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
}
]
