Collect.js merge() Method

The merge() method is used to merge the given object into the original collection. If the key of a given object is the same as the collection object then it overwrites the value of the key.
Syntax:
collect(array).merge(object)
Parameters: The collect() method takes one argument that is converted into the collection and then the merge() method is applied to it. The merge() method holds the object as a parameter.
Return Value: This method returns the collection of merged elements.
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 merge() method in collect.js:
Example 1: Filename: index.js
Javascript
// Requiring the module const collect = require('collect.js'); Â Â let obj = ['Geeks', 'zambiatek']; Â Â // Function call const collection = collect(obj); Â Â const merged_val = collection.merge(['Welcome', 'GFG']); Â Â // Printing the merged collection console.log(merged_val.all()); |
Run the index.js file using the following command:
node index.js
Output:
[ 'Geeks', 'zambiatek', 'Welcome', 'GFG' ]
Example 2: 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', Â Â Â Â } ]; Â Â // Function call const collection = collect(obj); Â Â const merged_val = collection.merge({ Â Â Â Â address: 'Noida', Â Â Â Â school: 'zambiatek', }); Â Â // Printing the merged collection console.log(merged_val.all()); |
Run the index.js file using the following command:
node index.js
Output:
[
{ name: 'Rahul', dob: '25-10-96' },
{ name: 'Aditya', dob: '25-10-96' },
address: 'Noida',
school: 'zambiatek'
]



