Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to elegantly merge multiple objects with overlapping keys?

Let's consider multiple objects with overlapping keys, where each key indicates a week of the year and the values are objects of integer test results, like

const ab_tests = { week1: { a: 4, b: 6 }, week2: { a: 0, b: 9 } };
const cd_tests = { week2: { c: 2, d: 5 }, week3: { c: 6, d: 7 } };
const xy_tests = { week1: { x: 1, y: 1 }, week4: { x: 100, y: 123 } };

What is an elegant way to merge them to a single object that contains all weeks as keys and the values as merged-objects, such that:

const merged_tests = {
  week1: { a: 4, b: 6, x: 1, y: 1 },
  week2: { a: 0, b: 9, c: 2, d: 5 },
  week3: { c: 6, d: 7 },
  week4: { x: 100, y: 123 },
};
like image 606
benito_h Avatar asked Dec 01 '25 10:12

benito_h


1 Answers

  • Using Array#reduce, iterate over the objects while updating the final one (accumulator)
  • In each iteration, using Object#entries and Array#forEach, iterate over the pairs of the current object and update the final one

const ab_tests = { week1: { a: 4, b: 6 }, week2: { a: 0, b: 9 } };
const cd_tests = { week2: { c: 2, d: 5 }, week3: { c: 6, d: 7 } };
const xy_tests = { week1: { x: 1, y: 1 }, week4: { x: 100, y: 123 } };

const merged = [ab_tests, cd_tests, xy_tests].reduce((merged, current) => {
  Object.entries(current).forEach(([key, value]) => {
    merged[key] ??= {};
    merged[key] = { ...merged[key], ...value };
  });
  return merged;
}, {});

console.log(merged);
like image 111
Majed Badawi Avatar answered Dec 03 '25 00:12

Majed Badawi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!