Home > Web Front-end > JS Tutorial > How Can I Merge Two Arrays of Objects Based on a Shared Key Without Explicit Key Iteration?

How Can I Merge Two Arrays of Objects Based on a Shared Key Without Explicit Key Iteration?

Linda Hamilton
Release: 2024-12-08 22:06:12
Original
286 people have browsed it

How Can I Merge Two Arrays of Objects Based on a Shared Key Without Explicit Key Iteration?

Merging Arrays of Objects Based on a Key

Objective

The task is to merge two arrays of objects based on a common key without iterating through their keys.

Example Scenario

Consider the following two arrays:

Array 1:
[
  { id: "abdc4051", date: "2017-01-24" },
  { id: "abdc4052", date: "2017-01-22" }
]

Array 2:
[
  { id: "abdc4051", name: "ab" },
  { id: "abdc4052", name: "abc" }
]
Copy after login

The goal is to merge these arrays based on the id key to obtain:

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

Solution without Iterating Through Keys

To achieve this without iterating through object keys:

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 code uses the Object.assign() method to merge the properties of objects at the same index in both arrays. The result is a new array with the combined properties of both arrays.

The above is the detailed content of How Can I Merge Two Arrays of Objects Based on a Shared Key Without Explicit Key Iteration?. 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