Sometimes, we want to replace objects in array with JavaScript.
In this article, we’ll look at how to replace objects in array with JavaScript.
How to replace objects in array with JavaScript?
To replace objects in array with JavaScript, we can use the array map
method.
For instance, we write
const mapped = arr1.map((obj) => arr2.find((o) => o.id === obj.id) ?? obj);
to call arr1.map
with a callback that maps the entry in arr1
to an object with the same id
value in arr2
if it exists.
Otherwise, it returns the obj
object in arr1
.
Conclusion
To replace objects in array with JavaScript, we can use the array map
method.