[Chartjs]-Creating dynamic object to reorganize API response using Typescript

2👍

You can get all unique sku by using array#map and Set. Once you have this array, you can create an order object which will map sku with index, which will be used to assign value to data for a given sku value.

Now, using array#reduce you can group the data based on month and populate the data based on the sku value.

const dataToFormat = [ { sku: 'Data 1', month: 'Jun', value: 20 }, { sku: 'Data 2', month: 'Jun', value: 25 }, { sku: 'Data 3', month: 'Jun', value: 35 }, { sku: 'Data 5', month: 'Jun', value: 10 }, { sku: 'Data 1', month: 'Jul', value: 20 }, { sku: 'Data 2', month: 'Jul', value: 30 }, { sku: 'Data 1', month: 'Aug', value: 20 }, { sku: 'Data 2', month: 'Aug', value: 30 }, { sku: 'Data 3', month: 'Aug', value: 15 }, { sku: 'Data 4', month: 'Aug', value: 20 }, { sku: 'Data 5', month: 'Aug', value: 15 } ],
      uniqueSku = [...new Set(dataToFormat.map(item => item.sku))],
      order = Object.fromEntries(uniqueSku.map((v,i) => ([v, i]))),
      result = Object.values(dataToFormat.reduce((r, {month, value, sku}) => {
        r[month] ||= {data: Array(uniqueSku.length).fill(null), label: month, stack: 'sameStack'};
        r[month].data[order[sku]] = value;
        return r;
      },{}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Leave a comment