Within my table, I have implemented a feature that allows the display of only selected columns at a time.
To achieve this, I store the chosen columns (table headings) in an array called selectedTableHeaders
.
The next step is to filter out a new array based on the properties listed in the selectedTableHeaders
, ensuring that only the selected columns are displayed in the table data.
In addition, it's crucial to maintain the correct order of the tableData. For example, if a user disables table header 3, then table header 6, and later enables 3 again, 3 should be added back in its original position. This means reordering the tableData according to the table headers as well.
What would be the best solution for achieving this?
const selectedTableHeaders = [
"table_header_1",
"table_header_3",
"table_header_5",
"table_header_6"
]
tableData [
{
"rowData": {
"table_header_1": "0",
"table_header_2": "data 2",
"table_header_3": "US",
"table_header_4": "data 4",
"table_header_5": "-",
"table_header_6": "data 6"
}
},
{
"rowData": {
"table_header_1": "0",
"table_header_2": "test 2",
"table_header_3": "GB",
"table_header_4": "test 4",
"table_header_5": "Y",
"table_header_6": "test data 6"
}
},
{
"rowData": {
"table_header_1": "0",
"table_header_2": "test 2",
"table_header_3": "DE",
"table_header_4": 70000118,
"table_header_5": "-",
"table_header_6": "test table 6"
}
}
]
I attempted to tackle this issue with the following approach:
this.tableData.forEach((tableItem) => {
const newArray = Object.assign(...selectedTableHeaders.map(k => ({ [k]: tableItem[k] })));
})
However, I am not getting the values in the newArray as expected. Is there a more effective way to handle this process and also retrieve the property values in the new array?
The goal is to generate a new array containing only the selected columns and ensure the correct ordering of the table data based on the table headings.
For instance:
If the heading order is:
"table_header_2",
"table_header_1",
"table_header_5",
"table_header_4"
The corresponding rowData should look like this:
"rowData": {
"table_header_2": "data 2 ",
"table_header_1": "0",
"table_header_5": "-",
"table_header_4": "data 4",
}