Reputation: 3
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.
Upvotes: 0
Views: 2150
Reputation: 82
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);
Upvotes: 0
Reputation: 33736
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; }
Upvotes: 1