Filter Array Based On It's Keys By Another Array
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: '
Solution 1:
You could take the wanted keys and map a new array with new objects with only the wanted properties.
functiongetProperties(array, keys) {
return array.map(o =>Object.assign(...keys.map(k => ({ [k]: o[k] }))));
}
var data = [{ id: "1", name: "A", description: "number 1" }, { id: "2", name: "B", description: "number 2" }];
console.log(getProperties(data, ['id', 'name']));
.as-console-wrapper { max-height: 100%!important; top: 0; }
An even shorter approach with Object.fromEntries
.
functiongetProperties(array, keys) {
return array.map(o =>Object.fromEntries(keys.map(k => [k, o[k]])));
}
var data = [{ id: "1", name: "A", description: "number 1" }, { id: "2", name: "B", description: "number 2" }];
console.log(getProperties(data, ['id', 'name']));
.as-console-wrapper { max-height: 100%!important; top: 0; }
Solution 2:
Try this and it works:
var data = [{
id: "1",
name: "A",
description: "number 1"
},
{
id: "2",
name: "B",
description: "number 2"
}
];
var selectedColumns = ["id", "name"];
if (selectedColumns) {
if (selectedColumns.length != 0) {
var data = data.filter(function(item) {
var keys = Object.keys(item)
keys.forEach(function(key) {
if (!selectedColumns.includes(key)) {
delete item[key];
}
})
returntrue
})
}
console.log(data);
}
Post a Comment for "Filter Array Based On It's Keys By Another Array"