Open In App

Collect.js replace() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The replace() method is used to replace the elements of the original collection that match the given string or numeric keys. If the key given in the object matches with a key in the collection, then its value is replaced, otherwise, if the key does not match, then it is added to the collection.

Syntax:

collect(array).replace(object)

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

Return Value: This method returns the collection elements with replaced value.

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

Example 1:

Javascript




const collect = require('collect.js');
  
const collection =
  collect(['Geeks', 'GFG', 'GeeksforGeeks']);
  
const replaced =
  collection.replace({ 1: 'Welcome' });
  
console.log(replaced.all());


Output:

{ '0': 'Geeks', '1': 'Welcome', '2': 'GeeksforGeeks' }

Example 2:

Javascript




const collect = require('collect.js');
  
const collection = collect({
    name: 'Rahul',
    age: 25,
    section: 'A',
    marks: 88,
    address: 'Noida'
});
  
const replaced = collection.replace({
    name: 'Rajesh',
    marks: 45
});
  
console.log(replaced.all());


Output:

{ name: 'Rajesh', age: 25, section: 'A', marks: 45, address: 'Noida' }

Last Updated : 30 Nov, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads