-1

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}
]
Nguyễn Văn Phong
  • 11,572
  • 15
  • 21
  • 43
developer
  • 1,210
  • 3
  • 14
  • 44
  • This seems like an [X/Y Problem](https://xyproblem.info/) to me. *Why* do you need to transform the array like this? – Logan Devine Apr 08 '21 at 15:02
  • With a `for` loop ? I don't really understand the question. Where are you stuck and what did you try ? For date conversions, you can use [moment](https://momentjs.com/) – Arnaud Denoyelle Apr 08 '21 at 15:03

3 Answers3

1

One way to do it :

datas.map(mydata => {
  const value = {
    category: mydata.category
  };
    
  mydata.data.forEach(d => value[d.date]= d.value);
 
  return value;
});
Tkim
  • 172
  • 6
1

Assuming your problem is with converting the value to a property, you can do it this way (For the date formatting check here How to format a JavaScript date):

[ 
  {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}] }
].map(x=> {return {category: x.category, [x.data[0].date.toString()] : x.data[0].value}})

enter image description here

ShayD
  • 401
  • 4
  • 11
0

You can use Array#map to create a new array in this way.

const yourArray = [{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}]}];

const result = yourArray.map(({category, data}) => {
  const otherProps = data.reduce((acc, {date, value}) => {
    acc[date] = value;
    return acc;
  }, {});
  return {category, ...otherProps};
});
console.log(result);
Nguyễn Văn Phong
  • 11,572
  • 15
  • 21
  • 43