This issue has cropped up in various scenarios and programming languages, and I have always managed to find a workaround. However, I am now hoping to establish a proper pattern to address this problem once and for all. It typically arises when joining SQL tables. Instead of making separate calls for items and comments, I know there must be a way to retrieve all the information in a single call and then flatten the result.
My goal is to transform an array structured like this:
[
{
itemId: 1,
comments: {
commentId: 1
}
},
{
itemId: 1,
comments: {
commentId: 2
}
},
{
itemId: 2,
comments: {
commentId: 3
}
}
]
Into the following format:
[
{
itemId: 1,
comments: [
{
commentId: 1
},
{
commentId: 2
}
]
},
{
itemId: 2,
comments: [
{
commentId: 3
}
]
}
]