Home > Web Front-end > JS Tutorial > How Can I Efficiently Merge Two Arrays of Objects Based on a Common Key?

How Can I Efficiently Merge Two Arrays of Objects Based on a Common Key?

Mary-Kate Olsen
Release: 2024-12-07 09:14:16
Original
327 people have browsed it

How Can I Efficiently Merge Two Arrays of Objects Based on a Common Key?

Merging Arrays of Objects with a Common Key

Consider two arrays of objects:

Array 1:
[
  { id: "abdc4051", date: "2017-01-24" },
  { id: "abdc4052", date: "2017-01-22" }
]
Copy after login
Array 2:
[
  { id: "abdc4051", name: "ab" },
  { id: "abdc4052", name: "abc" }
]
Copy after login

To merge these arrays based on the id property, a concise solution is to leverage the map() function and Object.assign().

Utilizing map(), we iterate through Array 1. For each object, we create a new object that combines the properties of both objects at the same index in Array 1 and Array 2. This new object is stored in arr3.

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

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

let arr3 = arr1.map((item, i) => Object.assign({}, item, arr2[i]));

console.log(arr3);
Copy after login

This achieves the desired result:

[
  { id: "abdc4051", date: "2017-01-24", name: "ab" },
  { id: "abdc4052", date: "2017-01-22", name: "abc" }
]
Copy after login

The above is the detailed content of How Can I Efficiently Merge Two Arrays of Objects Based on a Common Key?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template