Categories
JavaScript Answers

How to merge JavaScript objects in array with same key?

Spread the love

Sometimes, we want to merge JavaScript objects in array with same key.

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

How to merge JavaScript objects in array with same key?

To merge JavaScript objects in array with same key, we use some array methods.

For instance, we write

const array = [
  { name: "foo1", value: "val1" },
  { name: "foo1", value: ["val2", "val3"] },
  { name: "foo2", value: "val4" },
];

const result = array.reduce((acc, { name, value }) => {
  acc[name] ??= { name, value: [] };
  if (Array.isArray(value)) {
    acc[name].value = acc[name].value.concat(value);
  } else {
    acc[name].value.push(value);
  }
  return acc;
}, {});

console.log(Object.values(result));

to call array.reduce with a callback that gets the values from objects in array and put them in as the property of the acc object.

In it, we assign { name, value: [] } to acc[name] if acc[name] is undefined.

Then if value is an array, we call concat to put value in the acc[name].value array.

Otherwise, we call push to add value into acc[name].value.

acc is returned at the end.

Conclusion

To merge JavaScript objects in array with same key, we use some array methods.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.