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.

2

2 Answers 2

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; }

Sign up to request clarification or add additional context in comments.

1 Comment

This is correct, thank you so much. I spent way too much time trying to figure this out on my own.
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.