The replaceRecursive() method is similar to the replace() method but it works recursively and this method will recurse into arrays and the inner values are treated with the same replacement process.
Syntax:
collect(array).replaceRecursive(object)
Parameters: The collect() method takes one argument that is converted into the collection and then replaceRecursive() method is applied to it. The replaceRecursive() method holds the object or element as parameter.
Return Value: This method returns the collection elements with replaced value.
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 replaceRecursive() method in collect.js:
Example 1: Filename: index.js
Javascript
// Requiring the module const collect = require( 'collect.js' ); // Creating collection object const collection = collect([ [ 'Geeks' , 'GFG' , 'neveropen' ], [ 'Welcome' , 'to' , 'neveropen' ] ]); // Function call const replaced = collection.replaceRecursive( { 0: 'Hello' , 3: 'Welcome' }); // Printing values console.log(replaced.all()); |
Run the index.js file using the following command:
node index.js
Output:
{ '0': 'Hello', '1': { '0': 'Welcome', '1': 'to', '2': 'neveropen' }, '3': 'Welcome' }
Example 2: Filename: index.js
Javascript
// Requiring the module const collect = require( 'collect.js' ); const obj = [ { name: 'Rahul' , marks: 88 }, { name: 'Aditya' , marks: 78 }, { name: 'Abhishek' , marks: 87 } ]; // Creating collection object const collection = collect(obj); // Function call const replaced = collection.replaceRecursive( { 0: 'Welcome' , 3: 'neveropen' }); // Printing values console.log(replaced.all()); |
Run the index.js file using the following command:
node index.js
Output:
{ '0': 'Welcome', '1': { name: 'Aditya', marks: 78 }, '2': { name: 'Abhishek', marks: 87 }, '3': 'neveropen' }