Saturday, October 25, 2025
HomeLanguagesJavascriptCollect.js replaceRecursive() Method

Collect.js replaceRecursive() Method

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'
}
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS