how to merge 2 object array by the same key with lodash

Merging two object arrays by the same key can be a tricky process. Fortunately, lodash provides a simple, yet robust, way to do it.

Using lodash's merge() method, you can easily merge two object arrays using a common key. The merge() method takes two objects as parameters and combines them into a single object.

For example, let's say you have two object arrays with a common key "id".


  var arr1 = [
    { id: 1, name: "John" },
    { id: 2, name: "Jane" },
  ]

  var arr2 = [
    { id: 1, age: 20 },
    { id: 2, age: 30 },
  ]

You can use lodash's merge() method and a for-loop to merge these two object arrays.


  var mergedArray = [];

  for (var i = 0; i < arr1.length; i++) {
    mergedArray.push(
      _.merge(arr1[i], arr2[i])
    );
  }

This will create a new array with the following values:


  [
    { id: 1, name: "John", age: 20 },
    { id: 2, name: "Jane", age: 30 },
  ]

This is just one way of merging two object arrays with a common key. There are several other ways of doing it such as using the reduce() method, or using the spread operator.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe