0

I want to modify the data that API provides to client. I can only retrieve the unique category value using Set. Then I'm stuck how to proceed further.

const serverData = [
    {
        category: 'address',
        label: 'Street',
        type: 'text'
    },
    {
        category: 'address',
        label: 'Country',
        type: 'text'
    },
    {
        category: 'person',
        label: 'FirstName',
        type: 'text'
    },
    {
        category: 'person',
        label: 'LastName',
        type: 'text'
    }
];

I want the above to be modified like below. There can be many categories

const modifiedData = {
    address : [
        {
            label: 'Street',
            type: 'text'
        },
        {
            label: 'Country',
            type: 'text'
        },
    ],
    person : [
        {
            label: 'FirstName',
            type: 'text'
        },
        {
            label: 'LastName',
            type: 'text'
        }
    ]
};

Please help me achieve this. Thanks in advance!

VladNeacsu
  • 1,268
  • 16
  • 33
Hariharan Seenu
  • 45
  • 1
  • 11

1 Answers1

2

You could use the reduce function to format your data. Here is an example:

const serverData = [
  {
    category: 'address',
    label: 'Street',
    type: 'text'
  }, {
    category: 'address',
    label: 'Country',
    type: 'text'
  }, {
    category: 'person',
    label: 'FirstName',
    type: 'text'
  }, {
    category: 'person',
    label: 'LastName',
    type: 'text'
  }
];

const formatData = data => {
  return data.reduce((result, item) => ({
    ...result,
    [item.category] : [
      ...(result[item.category] || []),
      item
    ]
  }), {});
}

console.log(formatData(serverData));
giuseppedeponte
  • 2,366
  • 1
  • 9
  • 19