I have an array of objects like this:
const myObj = [
{
id: 2,
text: "apple",
category: "fruit"
},
{
id: 2,
text: "chocolate",
category: "sweets"
},
{
id: 1,
text: "banana",
category: "fruit"
},
{
id: 1,
text: "cookie",
category: "sweets"
}
]
I want to transform in something like this:
const data = [
{
category: 'fruit',
data: [
{
id: 1,
text: 'kiwi',
category: 'fruit',
},
{
id: 3,
text: 'apple',
category: 'fruit',
},
],
},
{
category: 'sweets',
data: [
{
id: 3,
text: 'cookie',
category: 'sweets',
},
{
id: 4,
text: 'chocolate',
category: 'sweets',
},
],
},
];
I have done a reduce on the myObj
like this:
const groupByCategory = (prev, curr) => {
prev[curr.category] = [...prev[curr.category] || [], curr]
return prev;
}
const result = myObj.reduce(groupByCategory, {})
And I have now this output:
{
fruit: [ { id: 2, text: 'apple', category: 'fruit' },
{ id: 1, text: 'banana', category: 'fruit' }
],
sweets: [
{ id: 2, text: 'chocolate', category: 'sweets' },
{ id: 1, text: 'cookie', category: 'sweets' }
]
}
Which is closer but not still the desired output. How can I do? Thanks.