-1

I am trying to solve this and keep getting stuck. I am currently trying to do this with lodash but open to any solution:

EDIT: I've done many searches and the suggested links are not the desired output

Array structure:

[
    { "date": "2022-03-01", "A": 11549 },
    { "date": "2022-03-01", "B": 4536 }
]

to become

[
    { "date": "2022-03-01", "A": 11549, "B": 4536 },
]
sn4ke
  • 587
  • 1
  • 14
  • 30
  • I smell reduce. – kelsny May 03 '22 at 15:26
  • 2
    Does this answer your question? [How can I group an array of objects by key?](https://stackoverflow.com/questions/40774697/how-can-i-group-an-array-of-objects-by-key) – evolutionxbox May 03 '22 at 15:26
  • 1
    Does this answer your question? [Merge two array of objects based on a key](https://stackoverflow.com/questions/46849286/merge-two-array-of-objects-based-on-a-key) – Anurag Srivastava May 03 '22 at 15:27

1 Answers1

0

Would this work for you ?

const arr = [
  { date: '2022-03-01', A: 11549 },
  { date: '2022-03-01', B: 4536 },
  { date: '2022-03-01', C: 8000 },
  { date: '2022-03-01', D: 4000, F: 7500 },
  { date: '2022-04-02', A: 4536 },
];

const r = Object.values(arr.reduce((o, curr) => {
  if (o[curr.date]) {
    for (const entry of Object.entries(curr)) o[curr.date][entry[0]] = entry[1];
  } else o[curr.date] = curr;
  return o;
}, {}))

console.log(r);
Cesare Polonara
  • 3,473
  • 1
  • 9
  • 19