-3

I have looked through a lot of the answers here on StackOverflow but can't quite find what I'm looking for. I have an array of objects like

const arr = [
   {id: 1, title: "Foo", time: "18:00"},
   {id: 2, title: "Bar", time: "20:00"},
   {id: 3, title: "Foo", time: "21:00"}
]

The output I'm looking for should be aggregated by the title property of the objects in arr, ie.

const output = [
{title: "Foo", i: [
                    {id: 1, time: "18:00"},
                    {id: 3, time: "21:00"}
                  ]
},
{title: "Bar", i: [
                    {id: 2, time: "20:00"},
                  ]
}]
  • If [search for the title](https://www.google.com/search?hl=en&q=How%20to%20group%20the%20objects%20by%20key%20in%20an%20array%3F%20site%3Astackoverflow.com) of your question I get suitable other questions on SO in the first ten results... -> [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – Andreas Sep 04 '21 at 12:34
  • Try using lodash, as seen here: https://stackoverflow.com/questions/40774697/how-to-group-an-array-of-objects-by-key – Lior Pollak Sep 04 '21 at 13:04
  • @LiorPollak Why? Lodash just for this is overkill... All you need is `.reduce()` or `.forEach()` or a plain-old `for` loop. – Andreas Sep 04 '21 at 13:46
  • @Andreas I’m a bit of a dinosaur here, but lodash does this effectively and nicely. I suppose you can do the same with vanilla js, of course – Lior Pollak Sep 04 '21 at 13:53
  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. – Community Sep 08 '21 at 17:34

1 Answers1

0

You can collect all the appropriate titles under an objec key via .reduce and then make this collector object an array of its values via Object.values():

const arr = [
   {id: 1, title: "Foo", time: "18:00"},
   {id: 2, title: "Bar", time: "20:00"},
   {id: 3, title: "Foo", time: "21:00"}
]

const output = Object.values(arr.reduce(
  (acc, { id, title, time }) => {
    acc[title] ??= { title, i: [] };
    acc[title].i.push({ id, time });
    return acc;
  },
  {},
));

console.log(JSON.stringify(output, null, '  '));
vsemozhebuty
  • 12,992
  • 1
  • 26
  • 26