0

I have an array of objects that looks like this:

var data = [
{Date: "01-01-2000", Banana: 10},
{Date: "01-01-2000", Apple: 15},
{Date: "01-01-2000", Orange: 20},
{Date: "01-02-2000", Banana: 25},
{Date: "01-02-2000", Apple: 30},
{Date: "01-02-2000", Orange: 35}];

And I would like to know how to merge the objects in this array by the same date values so that the following array is returned:

data = [
{Date: "01-01-2000", Banana: 10, Apple: 15, Orange: 20},
{Date: "01-02-2000", Banana: 25, Apple: 30, Orange: 35}];

My apologies if this is a duplicate question, I just have not been able to find an example where the key & value pairs are different in each object and so I thought I would at least ask.

  • Possible duplicate of [Sum javascript object propertyA values with same object propertyB in array of objects](https://stackoverflow.com/questions/19233283/sum-javascript-object-propertya-values-with-same-object-propertyb-in-array-of-ob) – lumio Oct 19 '18 at 19:51
  • Possible duplicate of [Combine json arrays by key, javascript](https://stackoverflow.com/questions/35903850/combine-json-arrays-by-key-javascript) – phadaphunk Oct 19 '18 at 19:52

2 Answers2

1

An alternative is using the function reduce to group the objects along with the function Object.values to extract the grouped objects.

var data = [{Date: "01-01-2000", Banana: 10},{Date: "01-01-2000", Apple: 15},{Date: "01-01-2000", Orange: 20},{Date: "01-02-2000", Banana: 25},{Date: "01-02-2000", Apple: 30},{Date: "01-02-2000", Orange: 35}],
    result = Object.values(data.reduce((a, c) => {
      a[c.Date] = Object.assign(a[c.Date] || {}, c);
      return a;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Ele
  • 33,468
  • 7
  • 37
  • 75
0

Alternatively, you can use a for loop.

Try:

var data = [{Date: "01-01-2000", Banana: 10},{Date: "01-01-2000", Apple: 15},{Date: "01-01-2000", Orange: 20},{Date: "01-02-2000", Banana: 25},{Date: "01-02-2000", Apple: 30},{Date: "01-02-2000", Orange: 35}];
var obj = {};
for(var i = 0; i < data.length; i++){
   var date = data[i].Date;
   // Get previous date saved inside the result
   var p_date = obj[date] || {}; 
   // Merge the previous date with the next date
   obj[date] = Object.assign(p_date, data[i]);
}

// Convert to an array
var result = Object.values(obj);

console.log(result);
s.meijer
  • 3,403
  • 3
  • 26
  • 23
Mzndako
  • 72
  • 1
  • 4