Skip to main content
edited title
Link
200_success
  • 145.7k
  • 22
  • 191
  • 481

Refactoring callback hell in the function with several forEach loops Extracting data from vue-chartjs into an array of datasets

edited title
Link
Olga B
  • 155
  • 5

Refactoring callback hell in the function with several forEach loops

Source Link
Olga B
  • 155
  • 5

Refactoring callback hell in the function

I have a function which returns an array of datasets for a chart written with vue-chartjs. The getter getChartData returns an array with three objects with nested objects. I see that my function has a so called 'callback hell' and I want to refactor this.

getDatasets() {
  let datasetLabels = [];
  const obj = this.getChartData;
  Object.entries(obj).forEach((entry) => {
    datasetLabels = [...datasetLabels, ...Object.keys(entry[1])];
  });
  let datasets = [];
  [...new Set(datasetLabels)].forEach((item, index, arr) => {
    datasets.push({ label: item, backgroundColor: this.getColor(arr, index), data: [] });
  });
  Object.entries(obj).forEach((el) => {
    const datasetData = Object.entries(el[1]);
    datasetData.forEach(
      (item) => {
        datasets = datasets.map((e) => {
          if (e.label === item[0]) {
            e.data.push(item[1].median);
          }
          return e;
        });
      });
  });
  return datasets;
},