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' , 'neveropen' ]; // 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', 'neveropen', '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: 'neveropen' , }); // 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: 'neveropen' ]