LWang
LWang

Reputation: 95

How to merge or concat data by key value in array of object?

I am trying to sort an array and concat data with the same "date" value together into an array.

So far I tried .map/.foreach method to loop around date variable and group all the other property as an object, but I get confused on how to combine data with the same data key.

Data I am working on :

let rawdata = [ { 'date': 'a', 'time': 'b', 'value1': 123, 'value2': 234 },
  { 'date': 'a', 'time': 'c', 'value1': 127, 'value2': 294 },
  { 'date': 'b', 'time': 'c', 'value1': 127, 'value2': 294 }]

My goal:

target = [ { 'date': 'a', 
             'data': [{ 'time': 'b', 'value1': 123, 'value2': 234 }, 
                      { 'time': 'c', 'value1': 127, 'value2': 294 }] },
           { 'date': 'b', 
               data: [{ 'time': 'c', 'value1': 127, 'value2': 294 }] }]

What I did:

let data1 = rawdata.map(item => {
  return {
    date: item.date,
    data: [
      { time: item.time,
        value1: item.value1,
        value2: item.value2
      }
    ]
  }
})

How to concat data1 sorting by the key of date?

Upvotes: 1

Views: 44

Answers (1)

Jack Bashford
Jack Bashford

Reputation: 44125

Use reduce:

let rawdata = [ { 'date': 'a', 'time': 'b', 'value1': 123, 'value2': 234 },{ 'date': 'a', 'time': 'c', 'value1': 127, 'value2': 294 },{ 'date': 'b', 'time': 'c', 'value1': 127, 'value2': 294 }];
let target = Object.values(rawdata.reduce((acc, { date, ...rest }) => {
  if (acc[date]) {
    acc[date].data.push({...rest});
  } else {
    acc[date] = { date, data: [{ ...rest }] };
  }
  return acc;
}, {}));
console.log(target);
.as-console-wrapper { max-height: 100% !important; top: auto; }

Upvotes: 1

Related Questions