Skip to content
Advertisement

Combine objects from an array with the same date into new array of objects using Javascript

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.

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement