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

How to merge two arrays of objects by ID using lodash?

1个答案

1

When working with JavaScript data operations, the Lodash library provides numerous practical functions to simplify array and object manipulation. If you have two arrays of objects, each with an id property serving as a unique identifier, you can use Lodash's merge or _.unionBy functions to merge the two arrays based on id.

Here are the specific implementation steps and code examples:

Step 1: Import the Lodash Library

Ensure that the Lodash library is already imported in your project. If it is not installed, you can install it via npm:

bash
npm install lodash

Step 2: Prepare the Data

Assume we have two arrays of objects as follows:

javascript
const array1 = [ { id: 1, name: "Alice" }, { id: 2, name: "Bob" } ]; const array2 = [ { id: 2, name: "Robert" }, { id: 3, name: "Charlie" } ];

Step 3: Merge Arrays Using Lodash

We can use _.unionBy to merge the arrays, which combines them based on the specified property (in this case, id), and automatically handles duplicates by retaining the first occurrence.

javascript
import _ from 'lodash'; const mergedArray = _.unionBy(array1, array2, 'id'); console.log(mergedArray);

Output Result

javascript
[ { id: 1, name: "Alice" }, { id: 2, name: "Bob" }, { id: 3, name: "Charlie" } ]

In this example, the object with id: 2 appears first in array1, so Lodash retains the version from array1 ("Bob") and does not select the version from array2 ("Robert").

Summary

Using Lodash's _.unionBy function, you can conveniently merge two arrays of objects based on a specified key (such as id), automatically resolving duplicate items. This approach is highly useful for merging datasets from different sources.

2024年6月29日 12:07 回复

你的答案