[Vuejs]-How to map data using vue js in table form?

0👍

First you will have to make an array of all available headers which is dynamic since it can vary based on monthTotalHours data

You can use this code to make it easy to use

const missingReports = [
  {
    empId: "1234",
    empName: "Aarohi",
    monthTotalHours: {
      "11-2022": { allocation: 32, totalHoursMissing: 6, difference: 21 },
      "12-2022": { allocation: 91, totalHoursMissing: 3, difference: 45 }
    }
  },
  {
    empId: "2345",
    empName: "Aarush",
    monthTotalHours: {
      "11-2022": { allocation: 10, totalHoursMissing: 2, difference: 21 }
    }
  }
];

const headers = ["empId", "empName"];
const months = [
  "Jan",
  "Feb",
  "Mar",
  "Apr",
  "May",
  "Jun",
  "Jul",
  "Aug",
  "Sep",
  "Oct",
  "Nov",
  "Dec"
];

const transformed_data = missingReports.map((report) => {
  // add columns to header;
  let rprt = {
    empId: report.empId,
    empName: report.empName
  };

  for (const date in report.monthTotalHours) {
    let [month, year] = date.split("-");
    let column_prefx = `${months[month - 1]}${year}`;
    let columns = [
      `${column_prefx}al`,
      `${column_prefx}hr`,
      `${column_prefx}dif`
    ];
    if (!headers.includes(columns[0])) {
      headers.push(...columns);
    }
    // add value with generated column name to the report
    const date_data = {
      [columns[0]]: report.monthTotalHours[date].allocation,
      [columns[1]]: report.monthTotalHours[date].totalHoursMissing,
      [columns[2]]: report.monthTotalHours[date].difference
    };
    rprt = { ...rprt, ...date_data };
  }

  return rprt;
});

console.log(transformed_data)
console.log(headers)

Now Since you have all the headers beforehand you can simply print those headers

Here comes the tricky part.

I transformed the data so that monthTotalHours.date.allocation will be available as Nov2022hr which will reflect the header name

So, What you will have to do is run 2 loop, One for the reports and in that loop run another loop for headers where you will get the header name

Then you can just print the data like this e.g report[header name]

Of course you will have to print the header name using a loop aswell.

e.g for the table printing

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div>

  <table>
    <tr>
      <th v-for="header in headers">
        {{header}}
      </th>
    </tr>
  
  <tbody>
    <tr v-for="report in transformed_data">
      <td v-for="header in headers">
        {{report[header]}}
      </td>
    </tr>
  </tbody>
  </table>
</div>

Leave a comment