Categories
JavaScript Answers

How to merge objects by id with JavaScript?

Spread the love

Sometimes, we want to merge objects by id with JavaScript.

In this article, we’ll look at how to merge objects by id with JavaScript.

How to merge objects by id with JavaScript?

To merge objects by id with JavaScript, we use the map method and the spread operator.

For instance, we write

const a1 = [
  { id: 1, name: "test" },
  { id: 2, name: "test2" },
];
const a2 = [
  { id: 1, count: "1" },
  { id: 2, count: "2" },
];
const a3 = a1.map((t1) => ({ ...t1, ...a2.find((t2) => t2.id === t1.id) }));

to call a1.map with a callback that returns a new object with the properties of the object being looped through t1 spread into a new object.

And we get the object with the same id value as t1 with a2.find((t2) => t2.id === t1.id) and spread its properties into the same object.

The properties of the object that’s merged in the latest would override the property values of the items merged in earlier if they have the same property name.

Conclusion

To merge objects by id with JavaScript, we use the map method and the spread operator.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.