Open In App

Collect.js mergeRecursive() Method

The mergeRecursive() method is used to merge the given array or collection elements recursively with the original collection. When the key of the first collection elements matches with the key of the second collection, then the value of these keys are merged together into an array recursively.

Syntax:



collect(array).mergeRecursive(object)

Parameters: The collect() method takes one argument that is converted into the collection and then the mergeRecursive() method is applied to it. It holds an object or collection as a parameter.

Return Value: This method returns the merged collection elements.



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

Example 1:




const collect = require('collect.js');
  
let obj = ['Geeks', 'GeeksforGeeks'];
  
const collection = collect(obj);
  
const merged_val = collection
    .mergeRecursive(['Welcome', 'GFG']);
  
console.log(merged_val.all());

Output:

{ '0': [ 'Geeks', 'Welcome' ], '1': [ 'GeeksforGeeks', 'GFG' ] }

Example 2:




const collect = require('collect.js');
  
let obj = [
    {
        name: 'Rahul',
        dob: '25-10-96',
    },
    {
        name: 'Aditya',
        dob: '25-10-96',
    }
];
  
const collection = collect(obj);
  
const merged_val = collection.mergeRecursive({
    address: 'Noida',
    school: 'GeeksforGeeks',
});
  
console.log(merged_val.all());

Output:

{
  '0': { name: 'Rahul', dob: '25-10-96' },
  '1': { name: 'Aditya', dob: '25-10-96' },
  address: 'Noida',
  school: 'GeeksforGeeks'
}

Article Tags :