I’m building a custom web component that displays data in a table format. The component uses a special attribute called tableSettings to define how each column should work. This attribute contains info about the field name, display label, and column width as nested arrays.
Here’s how I set up the component:
<data-table tableSettings="['Name', 'Full Name', '40'], ['Email', 'Email Address', '60']"></data-table>
The component reads this attribute and sends it to a function that builds the table:
this.buildTable(records, tableElement, this.getAttribute('tableSettings'));
I need to use the tableSettings to filter which columns from my data should be shown. I grab the first data record to create table headers:
Object.keys(firstRecord).forEach(fieldName => {
if (tableSettings.map(config => config[0]).includes(fieldName)) {
const header = headerRow.insertCell();
header.textContent = config[1];
header.style.cssText = 'width: ${config[2]}%';
}
});
The problem is that tableSettings comes as a string and I can’t use .map() on it. When I try Array(tableSettings) or Array.from(tableSettings), I just get individual characters.
I also tried switching quotes:
<data-table tableSettings='["Name", "Full Name", "40"], ["Email", "Email Address", "60"]'></data-table>
And adding outer brackets:
<data-table tableSettings="[['Name', 'Full Name', '40'], ['Email', 'Email Address', '60']]"></data-table>
Nothing works except using eval() which I really don’t want to do for security reasons. How do I properly convert this string into a real nested array structure?