Collect.js replaceRecursive() Method
Last Updated :
30 Nov, 2020
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
const collect = require( 'collect.js' );
const collection = collect([
[ 'Geeks' , 'GFG' , 'GeeksforGeeks' ],
[ 'Welcome' , 'to' , 'GeeksforGeeks' ]
]);
const replaced = collection.replaceRecursive(
{ 0: 'Hello' , 3: 'Welcome' });
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': 'GeeksforGeeks' },
'3': 'Welcome'
}
Example 2: Filename: index.js
Javascript
const collect = require( 'collect.js' );
const obj = [
{
name: 'Rahul' ,
marks: 88
},
{
name: 'Aditya' ,
marks: 78
},
{
name: 'Abhishek' ,
marks: 87
}
];
const collection = collect(obj);
const replaced = collection.replaceRecursive(
{ 0: 'Welcome' , 3: 'GeeksforGeeks' });
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': 'GeeksforGeeks'
}
Share your thoughts in the comments
Please Login to comment...