Invisible-coder
Invisible-coder

Reputation: 159

How to Combine an object with the same key and NOT override the values?

I am trying to combine an array of objects by the same key and not override the values. Is it possible to combine the values into an array to that same key reference.

Consider this calendar object:

const calendar = [
   {date: "1999", month: "03"},
   {date: "1999", month: "01"},
   {date: "1998", month: "04"}
]

// My attempted with lodash:
let results = _(calendar )
    .groupBy('date')
    .value()

// my output (also returns an object)
results = {
     1998: {date: "1998", month: "04"}
     1999: {date: "1999", month: "03"}, {date: "1999", month: "01"}
}

// Acceptable Output #1: 
results = [
   {date: "1999", month: ["03", "01"]},
   {date: "1998", month: ["04"]}
]

// Acceptable Output #2:
results = {
     1998: [{month: "04"}]
     1999: [{month: "03"}, {month: "01"}]
}

// Acceptable Output #3:
results = [
   {"1999": ["03", "01"]},
   {"1998": ["04"]}
]


Or if have another alternative that works just fine. The end goal is to not override the values as I'm seeing all over stackoverflow...

Upvotes: 0

Views: 587

Answers (1)

random
random

Reputation: 7891

Instead of using lodash library, you can use reduce.

Output 3

const calendar = [
  {date: "1999", month: "03"},
  {date: "1999", month: "01"},
  {date: "1998", month: "04"}
];

const output = calendar
.reduce((a, {date, month}) => {
  if(!a[date]) {
    a[date] = [];
  }
  
  a[date].push(month);
  return a;
}, {});

console.log(output);

Output 2

const calendar = [
  {date: "1999", month: "03"},
  {date: "1999", month: "01"},
  {date: "1998", month: "04"}
];

const output = calendar
.reduce((a, {date, month}) => {
  if(!a[date]) {
    a[date] = [];
  }
  
  a[date].push({month});
  return a;
}, {});

console.log(output);

Output 1

const calendar = [
  {date: "1999", month: "03"},
  {date: "1999", month: "01"},
  {date: "1998", month: "04"}
];

const output = calendar
.reduce((a, {date, month}) => {
  if(!a[date]) {
    a[date] = {date, month: []};
  }

  a[date].month.push(month);
  return a;
}, {});

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

Upvotes: 1

Related Questions