I want to filter an array with data objects with it's keys based on another array.
I need to show/hide columns of a table, which is based on data like this:
var data = [{
id: "1",
name: "A",
description: "number 1"
},
{
id: "2",
name: "B",
description: "number 2"
}
]
This results in a table with three columns ("ID", "Name" and "Description") and two rows.
I now have a dropdown which contains one checkbox for each table header.
These inputs get stored in another array, so when you click "id" in the dropdown, the array looks like this:
var selectedColumns = ["id"]
..or when you select "id" and "name":
var selectedColumns = ["id", "name"]
I now want to filter my data array based on the selectedColumns array.
I already tried the filter function, but I can't wrap my head around on how to do it right:
if (selectedColumns) {
if (selectedColumns.length != 0) {
data = data.filter(function(item) {
var keys = Object.keys(item)
keys.forEach(function(key) {
if (!selectedColumns.includes(key)) {
delete item[key];
}
})
return true
})
}
Background: This table should be a reusable Vue component, so all the keys ("id", "name", ..) and the table headers change accordingly, which prevents hardcoding the logic.
datato have only the keys defined inselectedColumns?...I now want to filter my data array based on the selectedColumns array...Does this means you want to hide the columns which are not in theselectedColumnsarrays?filter, that's amap, like Nina's answer specifies.