I'm creating a custom, table-based HtmlElement (HTML5 Component). The HtmlElement has a custom columnConfiguration attribute to specify the database name, alias (if any) to display instead, and width (in percent) of each column to be displayed using an array of arrays:
<my-html-element columnConfiguration="['Id', 'Id', '0'], ['Description', 'Desc', '80'], ['Abbreviation', 'Abbrv', '20']"></my-html-element>
The custom element successfully reads the attribute value and passes it to a method that builds the table dynamically:
this.displayData(data, table, this.getAttribute('columnConfiguration'));
I'm also using the columnConfiguration attribute to filter out columns that are returned from the database but that I don't want to include in the table, so I want to check whether each returned column is included in the attribute value.
I select the first row of JSON data as firstItem from the returned dataset to create the table header using its property names:
Object.keys(firstItem).forEach(attributeName => {
if (columnConfiguration.map(item => item[0]).includes(attributeName)) {
const headerCell = headerRow.insertCell();
headerCell.textContent = item[1];
headerCell.style.cssText = 'width: ${item[2]}';
}
}
});
But columnConfiguration is coming through as a string, and the .map() call is failing.
I've tried casting columnConfiguration to Array, but I get an array of individual characters:
Array(columnConfiguration)
I've tried creating an array using Array.from() with the same result:
Array.from(columnConfiguration)
I've tried reversing the single and double quotes in the columnConfiguration attribute declaration:
<my-html-element columnConfiguration='["Id", "Id", "0"], ["Description", "Desc", "80"], ["Abbreviation", "Abbrv", "20"]'></my-html-element>
I've also tried including the enclosing square brackets of the "outer" array:
<my-html-element columnConfiguration="[['Id', 'Id', '0'], ['Description', 'Desc', '80'], ['Abbreviation', 'Abbrv', '20']]"></my-html-element>
And I've tried creating an new Array, using the attribute string:
new Array(columnConfiguration)
There doesn't seem to be a way to convert a string literal containing a JavaScript array of arrays to an actual array of arrays short of the dreaded (and horrifically insecure) eval().
What am I missing?
Note: I'm not interested at all in other ways to get this to work. I want to understand why this way isn't working and what I should do to get the result I want this way.
[["Id", ...)? Otherwise you're basically parsing arbitrary JavaScript.Array()constructor doesn't accept a string. You seem to be confusing it withJSON.parse()JSON.parseis able to handle array strings and parse them:console.log(JSON.parse(`[["Id", "Id", "0"], ["Description", "Desc", "80"], ["Abbreviation", "Abbrv", "20"]]`))works just fine. Your string does not have to be enclosed in{}.