Set columns dynamically

I am attempting to replicate a spreadsheet whereby the data looks like this:

+--------------------+---------+---------+---------+-----+
|        Date        | 01-2022 | 02-2022 | 03-2022 | ... |
+--------------------+---------+---------+---------+-----+
| http://google.com  | 100%    | 73%     | 100%    | ... |
| http://twitter.com | 50%     | 70%     | 100%    | ... |
| ...                | ...     | ...     | ...     | ... |
+--------------------+---------+---------+---------+-----+

The issue is that I have to build these monthly time buckets dynamically on my back end, and the percentages match for each site.

An example of the response I receive from my API is:

[
  {
    "url": "http://google.com",
    "percentagesByMonth": [
      {
        "month": "01-2022",
        "percent": 100
      },
      {
        "month": "02-2022",
        "percent": 73
      },
      ...
    ]
  },
  {
    "url": "http://twitter.com",
    "percentagesByMonth": [
      {
        "month": "01-2022",
        "percent": 50
      },
      {
        "month": "02-2022",
        "percent": 70
      },
      ...
    ]
  },
  ...
  "allMonths": ['01-2022', '02-2022', '03-2022', ... ]
]

How can I create a table which has the above desired output?
I can't seem to figure out how to use the dynamic column settings to have a column for each month.

Hey @krynv!

Since the you have the key (date) and value (percentage) for each month stored at the same level it looks like Object.fromEntries might be useful for constructing the appropriate object. You'd just need to extract the values of each which Object.values is perfect for. The expression

percentagesByMonth.map(Object.values)

should return something like

[
   ["01-2022", 100],
   ["02-2022", 73],
]

so, Object.fromEntries(percentagesByMonth.map(Object.values) should give you

{
  "01-2022": 100,
  "02-2022": 73,
}

which is looking like the start of the row you want.

All that's left is to add the site URL. This one's a bit weird but I think to get what you're going for you might having a column with the header Date that holds all the URLs, that should at least give you the visual you're looking for, though it won't really be reflected in the object structure:

{
  Date: "http://google.com",
  "01-2022": 100,
  "02-2022": 73,
}

Putting that all together in one big mapper on your data looks something like:

{{ data.map(site => ({date: site.url, ...Object.fromEntries(site.percentagesByMonth.map(Object.values))})) }}

:grimacing:

Not the prettiest, but let me know if it works!

1 Like

This looks like what I'm after. Thanks