Home >Web Front-end >JS Tutorial >How to Efficiently Merge JavaScript Objects by ID?

How to Efficiently Merge JavaScript Objects by ID?

DDD
DDDOriginal
2024-11-29 20:22:15579browse

How to Efficiently Merge JavaScript Objects by ID?

Merging JavaScript Objects by Id

Question:

How can I efficiently merge two JavaScript arrays of objects based on a common "id" property, adding additional data from the second array to the first?

Example:

var a1 = [{ id: 1, name: "test" }, { id: 2, name: "test2" }]
var a2 = [{ id: 1, count: "1" }, { id: 2, count: "2" }]

Desired Output:

var a3 = [{ id: 1, name: "test", count: "1" }, { id: 2, name: "test2", count: "2" }]

Solution:

Using ES6, you can achieve this with a concise solution:

const a3 = a1.map(t1 => ({ ...t1, ...a2.find(t2 => t2.id === t1.id) }));

This solution leverages the map() and find() methods:

  • map(): Iterates over each element in a1 and creates a new object.
  • find(): Finds the object in a2 with the same "id" as the current element in a1.
  • Spread Operator ( ... ): Combines the properties of the current element in a1 with the properties of the corresponding element in a2.

This method effectively merges the objects in a1 and a2 based on the "id" property, adding any additional properties from a2 to the resulting objects in a3.

The above is the detailed content of How to Efficiently Merge JavaScript Objects by ID?. 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