乐闻世界logo
搜索文章和话题

How to merge multiple array of object by ID in javascript?

1个答案

1

Merging multiple object arrays by ID in JavaScript is a common requirement, especially when handling similar data from various sources. There are several approaches to achieve this; one method leverages modern JavaScript features such as the Map object and the spread operator.

Assume we have two arrays, each containing objects with an id property and additional attributes. The goal is to merge these arrays so that objects sharing the same id merge their properties.

Example Data:

javascript
const array1 = [ { id: 1, name: 'Alice', age: 25 }, { id: 2, name: 'Bob', age: 30 } ]; const array2 = [ { id: 1, city: 'New York' }, { id: 2, city: 'Los Angeles' } ];

Merging Logic:

  1. Create a Map object to store each object using id as the key.
  2. Iterate through all arrays and add objects to the Map. If an object with the same id already exists, merge them.

Implementation Code:

javascript
function mergeArraysById(...arrays) { const mergedMap = new Map(); arrays.forEach(array => { array.forEach(item => { const existingItem = mergedMap.get(item.id); if (existingItem) { // Merge objects mergedMap.set(item.id, { ...existingItem, ...item }); } else { // Add new object mergedMap.set(item.id, item); } }); }); // Convert Map values to an array return Array.from(mergedMap.values()); } // Usage example const mergedArray = mergeArraysById(array1, array2); console.log(mergedArray);

Output Result:

plaintext
[ { id: 1, name: 'Alice', age: 25, city: 'New York' }, { id: 2, name: 'Bob', age: 30, city: 'Los Angeles' } ]

This approach uses Map to efficiently look up and merge objects by id. With the spread operator ..., we can easily merge properties of objects sharing the same id.

The advantage of this method is its clarity and efficiency, particularly when handling large datasets and frequent lookups. Additionally, it is easily extensible—for instance, by incorporating more complex merging logic or handling deep object merging.

2024年8月24日 01:36 回复

你的答案