Sometimes, we want to replace matched item with lodash and JavaScript.
In this article, we’ll look at how to replace matched item with lodash and JavaScript.
How to replace matched item with lodash and JavaScript?
To replace matched item with lodash and JavaScript, w can use the map function.
For instance, we write
const arr = [
{ id: 1, name: "Person 1" },
{ id: 2, name: "Person 2" },
];
const newArr = _.map(arr, (a) => {
return a.id === 1 ? { id: 1, name: "Person New Name" } : a;
});
to call Lodash map with the arr array and a callback that maps the entries in arr to new values.
If the id of the object in arr is 1, then we return a new object.
Otherwise, we return a as is.
Conclusion
To replace matched item with lodash and JavaScript, w can use the map function.