Categories
JavaScript Answers

How to merge two array of objects based on a key with JavaScript?

Spread the love

Sometimes, we want to merge two array of objects based on a key with JavaScript.

In this article, we’ll look at how to merge two array of objects based on a key with JavaScript.

How to merge two array of objects based on a key with JavaScript?

To merge two array of objects based on a key with JavaScript, we can use the array map and find methods and the spread operator.

For instance, we write

const arr1 = [
  { id: "abdc4051", date: "2017-01-24" },
  { id: "abdc4052", date: "2017-01-22" },
];

const arr2 = [
  { id: "abdc4051", name: "ab" },
  { id: "abdc4052", name: "abc" },
];

const mergeById = (a1, a2) =>
  a1.map((itm) => ({
    ...a2.find((item) => item.id === itm.id && item),
    ...itm,
  }));

console.log(mergeById(arr1, arr2));

to define the mergeById function.

In it, we call a1.map with a callback that has the contents of the object in a2 that has the same id of the current object in a1, which is itm and the itm object.

We find the object with the same id value as the one being looped through in a1 with

a2.find((item) => item.id === itm.id && item)

We spread the properties of each into a new object and return it.

Conclusion

To merge two array of objects based on a key with JavaScript, we can use the array map and find methods and the spread operator.

By John Au-Yeung

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

One reply on “How to merge two array of objects based on a key with JavaScript?”

Thanks for the reply and the article I understand it now.

item.id === itm.id && item

This is essential a shorthand if statement the above could be writen in its long form version as such.

if(item.id === itm.id) { return item; }

Thanks again for the article didn’t know the double ampersand worked in this fashion so has been good to learn about it!

Leave a Reply

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