Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

105
Vistas
Transforming array of objectes into another one but with some changes

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.

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda