1

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.

LuisTheDev
  • 113
  • 7
  • @trincot, op has already the result form the duplicate, but needs another format. – Nina Scholz Dec 18 '21 at 18:04
  • You'll need to map the output from your `.reduce()` and add the `category` and `data` properties and reassign the `fruit` to `category` key and `fruit` object to `data` key. – Randy Casburn Dec 18 '21 at 18:05
  • you need another transformation: `const result = Object.entries(myObj.reduce(groupByCategory, {})).map(([category, data]) => ({ category, data }))` – Nina Scholz Dec 18 '21 at 18:08
  • Added a few more links in the duplicate reference block: the top one seems to be about the exact same transformation. – trincot Dec 18 '21 at 18:11

0 Answers0