How to merge duplicate objects in array of objects with JavaScript?

Sometimes, we want to merge duplicate objects in array of objects with JavaScript.

In this article, we’ll look at how to merge duplicate objects in array of objects with JavaScript.

How to merge duplicate objects in array of objects with JavaScript?

To merge duplicate objects in array of objects with JavaScript, we can use the array map method.

For instance, we write:

const data = [{
    label: "Book1",
    data: "US edition"
  },
  {
    label: "Book1",
    data: "UK edition"
  },
  {
    label: "Book2",
    data: "CAN edition"
  }
];
const newData = [...new Set(data.map(d => d.label))].map(label => {
  return {
    label,
    data: data.filter(d => d.label === label).map(d => d.data)
  }
})

console.log(newData)

to merge the items with the label value together.

To do this, we get an array of labels without the duplicates with [...new Set(data.map(d => d.label))].

Then we call map again with a callback to return an object with the data properties from the objects that has the same label values.

As a result, newData is:

[
  {
    "label": "Book1",
    "data": [
      "US edition",
      "UK edition"
    ]
  },
  {
    "label": "Book2",
    "data": [
      "CAN edition"
    ]
  }
]

Conclusion

To merge duplicate objects in array of objects with JavaScript, we can use the array map method