Skip to content
the poor coder

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

Poor Man
Published
Reading time
1 min read

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".

Text

  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.

Text

  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:

Text

  [
    { 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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC