Home >Web Front-end >JS Tutorial >How to Efficiently Merge Two Object Arrays Based on a Key Without Iterating Object Keys?

How to Efficiently Merge Two Object Arrays Based on a Key Without Iterating Object Keys?

Barbara Streisand
Barbara StreisandOriginal
2024-12-29 02:43:14360browse

How to Efficiently Merge Two Object Arrays Based on a Key Without Iterating Object Keys?

Merging Object Arrays Based on a Key without Iterating over Object Keys

Consider the scenario of having two object arrays:

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

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

Our goal is to merge these arrays based on the id property, resulting in an array that combines the properties of both objects:

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

To achieve this efficiently without using a loop over Object keys, we can utilize the map() function:

const mergedArray = array1.map((item, index) => Object.assign({}, item, array2[index]));

This approach uses the Object.assign() method to merge the properties of corresponding objects from both arrays into a new combined object, which is then accumulated into the mergedArray.

The resulting merged array satisfies our requirement of combining the properties based on the shared id key, without the need for iterative loops over Object keys.

The above is the detailed content of How to Efficiently Merge Two Object Arrays Based on a Key Without Iterating Object Keys?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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