I’m building a custom web component that creates tables dynamically. The component uses a special attribute called tableSettings to define how columns should be displayed. This attribute contains nested arrays with column info like database field name, display label, and width percentage.
<custom-table tableSettings="['UserId', 'User ID', '15'], ['FullName', 'Name', '60'], ['Status', 'Active', '25']"></custom-table>
My 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 database columns appear in my table. I grab the first record from my data to create table headers:
Object.keys(firstRecord).forEach(fieldName => {
if (tableSettings.map(config => config[0]).includes(fieldName)) {
const cell = headerRow.insertCell();
cell.textContent = config[1];
cell.style.cssText = 'width: ${config[2]}%';
}
});
The problem is that tableSettings comes in as a string and I can’t use .map() on it. When I try to convert it with Array(tableSettings) or Array.from(tableSettings), I just get an array of individual characters instead of the nested structure I need.
I tried switching the quotes around:
<custom-table tableSettings='["UserId", "User ID", "15"], ["FullName", "Name", "60"]'></custom-table>
I also tried wrapping everything in outer brackets:
<custom-table tableSettings="[['UserId', 'User ID', '15'], ['FullName', 'Name', '60']]"></custom-table>
Nothing works. How can I properly convert this string representation into a real nested array without using eval() which I know is dangerous?