Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

96
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!