Q:

How can I merge object values if they have the same key?

I have an Array full of transactions and I want to divide it by day. It will be an array of date that is and array of transations. It may be a little messy but I want to return this structure.
What I tried to do returns me the structure I want, but I don't know how to merge duplicated key values.
This is the array
const transactions = [
  {
    name: "Salário",
    receiveDate: "2020-05-12T00:00:00.000Z",
    value: "1000",
  },
  {
    name: "Pagamento ",
    receiveDate: "2020-05-12T00:00:00.000Z",
    value: "2350",
  },
  {
    name: "Passagem no VEM",
    paidDate: "2020-05-02T00:00:00.000Z",
    value: "130",
  },
  {
    name: "Almoço",
    paidDate: "2020-05-08T00:00:00.000Z",
    value: "50",
  },
];

This is what I already tried by now
const days = [];
const finalArray = [];

for (let i = 0; i < transactions.length; i++) {
  transactions[i].day = transactions[i].receiveDate || transactions[i].paidDate;
  days.push(transactions[i].day);
}

const datesToMatch = [...new Set(days)].map((date) => {
  return { [date]: null };
});

transactions.map((transaction) => {
  datesToMatch.map((dayObject) => {
    const day = Object.keys(dayObject).toString();
    if (day === transaction.day) {
      finalArray.push({ [day]: [transaction] });
    }
  });
});

The output
[ { '2020-05-12T00:00:00.000Z': [ [Object] ] },
  { '2020-05-12T00:00:00.000Z': [ [Object] ] },
  { '2020-05-02T00:00:00.000Z': [ [Object] ] },
  { '2020-05-08T00:00:00.000Z': [ [Object] ] } ]

Expected output
[ { '2020-05-12T00:00:00.000Z': [ [Object, Object] ] },
  { '2020-05-02T00:00:00.000Z': [ [Object] ] },
  { '2020-05-08T00:00:00.000Z': [ [Object] ] } ]

Thanks!

A:

Explanation:

dates : extract dates from both fields
uniqueDates : build a Set and convert it into an array so it only has uniqueDates
dateToTransactions : map every unique date to an object with one key (itself) and filter every transaction that is equal to it.

const transactions = [{
    name: "Salário",
    receiveDate: "2020-05-12T00:00:00.000Z",
    value: "1000",
  },
  {
    name: "Pagamento ",
    receiveDate: "2020-05-12T00:00:00.000Z",
    value: "2350",
  },
  {
    name: "Passagem no VEM",
    paidDate: "2020-05-02T00:00:00.000Z",
    value: "130",
  },
  {
    name: "Almoço",
    paidDate: "2020-05-08T00:00:00.000Z",
    value: "50",
  },
];

const dates = transactions.map(x => {
  const received = x.receiveDate || [];
  const paid = x.paidDate || [];
  return received + paid;
});

const uniqueDates = [...new Set(dates)];

const dateToTransactions =
  uniqueDates.map(
    date => {
      sameDate = transactions.filter(x => x.receiveDate === date || x.paidDate == date);
      return {[date]: sameDate}; 
    });

console.log(dateToTransactions);

