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

How to Merge JavaScript Objects by ID?

Linda Hamilton
Release: 2024-12-04 22:47:15
Original
415 people have browsed it

How to Merge JavaScript Objects by ID?

Merging Objects by Id in JavaScript

In JavaScript, objects can be effectively merged to combine data from multiple sources. When dealing with arrays of objects, a common challenge is to merge objects by a specific field, often referred to as an id.

For instance, given the following arrays:

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

we want to combine them based on the 'id' field, resulting in the following:

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

Solution:

A concise and effective solution in ES6 is to utilize the native map function:

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

Here, we iterate through each object t1 in a1 and create a new object. Using the spread operator (...), we spread the properties from t1 into the new object.

To append properties from the matching object in a2, we use the find method to locate the object with the matching 'id'. We then spread the properties from this found object into the new object.

This approach elegantly combines data from the two arrays, producing the desired result. It is also extendable to handle more complex scenarios seamlessly.

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