Transform array using Typescript Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Transform array using Typescript without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have the following JSON array:

[ 
     {category: 'Category 1', data: [ {date: '01/04/2021', value: 10}, {date: '01/03/2021', value: 20}, {date: '01/02/2021', value: 5}] },
     {category: 'Category 2', data: [ {date: '01/04/2021', value: 8}, {date: '01/03/2021', value: 2}, {date: '01/02/2021', value: 15}] },
     {category: 'Category 3', data: [ {date: '01/04/2021', value: 7}, {date: '01/03/2021', value: 1}, {date: '01/02/2021', value: 5}] }
]

How can I transform the array to the following format using javascript / typescript?

[
     {category: 'Category 1', 'Apr 2021' : 10, 'Mar 2021' : 20, 'Feb 2021': 5},
     {category: 'Category 2', 'Apr 2021' : 8, 'Mar 2021' : 2, 'Feb 2021': 15},
     {category: 'Category 3', 'Apr 2021' : 7, 'Mar 2021' : 1, 'Feb 2021': 5}
]

Answer

One way to do it :

datas.map(mydata => {
  const value = {
    category: mydata.category
  };
    
  mydata.data.forEach(d => value[d.date]= d.value);
 
  return value;
});
We are here to answer your question about Transform array using Typescript - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji