Tengo una serie de objetos como este:
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" } ]Quiero transformarme en algo como esto:
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', }, ], }, ]; He hecho una reducción en myObj así:
const groupByCategory = (prev, curr) => { prev[curr.category] = [...prev[curr.category] || [], curr] return prev; } const result = myObj.reduce(groupByCategory, {})Y ahora tengo esta salida:
{ 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' } ] }Que está más cerca pero no sigue siendo la salida deseada. ¿Como lo puedo hacer? Gracias.