Categories
JavaScript Answers

How to replace objects in array with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *