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:
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:
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' }