Home > Software engineering >  make table and counter with methods of array in es6
make table and counter with methods of array in es6

Time:09-16

I have this code :

const column = Array.from({ length: 16 }, (_, i) => ({
  title: `${i   8}-${i   9}`,
  dataIndex: `${i   8}`,
}));
column.splice(0, 0, { title: 'day/time', dataIndex: 'day' });

const data = Array.from({ length: 7 }, (_, i) => ({
  day: `${i   1} of week`,
  8: <Checkbox />,
  9: <Checkbox />,
  10: <Checkbox />,
  11: <Checkbox />,
  12: <Checkbox />,
  13: <Checkbox />,
  14: <Checkbox />,
  15: <Checkbox />,
  16: <Checkbox />,
  17: <Checkbox />,
  18: <Checkbox />,
  19: <Checkbox />,
  20: <Checkbox />,
  21: <Checkbox />,
  22: <Checkbox />,
  23: <Checkbox />,
}));

and output is :

enter image description here

I think I can summarize the code of data and do not type all of the "checkbox" , while I'm using methods of ES6 .

any solutions?

CodePudding user response:

You can use fromEntries to transform the array of arrays of two items with key and value, to object properties and use spread operator

const data = Array.from({ length: 7 }, (_, i) => ({
      day: `${i   1} of week`,
      ...Object.fromEntries(Array.from({ length: 15 }, (_, i) => [i   8, <Checkbox />]))
}));

FOR TESTING PURPOSES, I wrap the component into a string to be a valid syntax with native javascript you can unwrap from string when you use it.

const data = Array.from({ length: 7 }, (_, i) => ({
      day: `${i   1} of week`,
      ...Object.fromEntries(Array.from({ length: 15 }, (_, i) => [i   8, "<Checkbox />"]))
}));

console.log(data)

CodePudding user response:

This will produce the whole table:

const row=Array(16).fill('<input type="checkbox" />'),
  [thd,tbd]=["thead","tbody"].map(t=>document.querySelector(t));

thd.innerHTML=`<tr><td>date\\time</td><td>${row.map((_,i)=>(i 8) "-" (i 9)).join("</td><td>")}</td></tr>`;
tbd.innerHTML=[...Array(7)].map((_,j)=>`<tr><td>day ${j 1}</td>
  <td>${row.join("</td><td>")}</td></tr>`).join("\n");
<table>
<thead></thead>
<tbody></tbody>
</table>

  • Related