Home > Net >  I dont get what I expect form the fucntion
I dont get what I expect form the fucntion

Time:03-29

this is what I have written

const DataFromDataBase : IDataFromDataBase = {
  label :['January', 'February', 'March', 'April', 'May', 'June', 'July'],
  datasets : [{datasetName:'Dataset1', data:[1,3,5,2,5,2,6]},{datasetName:'Dataset2', data:[4,6,5,2,5,2,6]} ],
}     


 const DatatoBarChartJS  = {
      label,
      datasets : dataFromDataBase.datasets.map((dataset)=>{
        {
          label:dataset.datasetName
          data : dataset.data
          backgroundColor: 'rgba(255, 99, 132, 0.5)'
        }
      })
    }

I expect to have below construction for DatatoBarChartJS

['January', 'February', 'March', 'April', 'May', 'June', 'July'],
 datasets: [
   {
     label: 'Dataset 1',
     data:[1,3,5,2,5,2,6] ,
     backgroundColor: 'rgba(255, 99, 132, 0.5)',
   },
   {
     label: 'Dataset 2',
     data:[4,6,5,2,5,2,6],
     backgroundColor: 'rgba(53, 162, 235, 0.5)',
   },
 ],

month names before datasets works fine but in datasets I get 2 empty arrays

it should be this enter image description here

but this is what I get enter image description here

why I cant produce what I expect

CodePudding user response:

The code in the question seems to use .map(x => {}); but missing the return.

Please try this:

 const DatatoBarChartJS  = {
      label,
      datasets : dataFromDataBase.datasets.map((dataset)=>{
        return {
          label:dataset.datasetName,
          data : dataset.data,
          backgroundColor: 'rgba(255, 99, 132, 0.5)'
        }
      })
    }

Kindly consider the following, if it is helpful:

 const DatatoBarChartJS  = {
      label,
      datasets : dataFromDataBase.datasets.map(
        ({datasetName, data}) => ({
          label: datasetName,
          data,
          backgroundColor: 'rgba(255, 99, 132, 0.5)'
        })
      )
    };

CodePudding user response:

This is because you are not returning anything from the map function. Take a look at the following code.

interface IDataset {
  datasetName: string;
  data: number[];
}

interface IDataFromDataBase {
  label: string[];
  datasets: IDataset[];
}

const DataFromDataBase: IDataFromDataBase = {
  label: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [
    { datasetName: "Dataset1", data: [1, 3, 5, 2, 5, 2, 6] },
    { datasetName: "Dataset2", data: [4, 6, 5, 2, 5, 2, 6] },
  ],
};

// INFERRED TYPE:
// const DatatoBarChartJS: {
//   label: string[];
//   datasets: {
//       label: string;
//       data: number[];
//       backgroundColor: string;
//   }[];
// }
const DatatoBarChartJS = {
  label: DataFromDataBase.label,
  datasets: DataFromDataBase.datasets.map((dataset) => {
    return {
      label: dataset.datasetName,
      data: dataset.data,
      backgroundColor: "rgba(255, 99, 132, 0.5)",
    };
  }),
};

console.log(DatatoBarChartJS);

  • Related