Yes, I know, there is already a question about how to filter objects in javascript, but look, I’m not asking how to do it, I’m asking about what would be the easiest way, the one which a noob like me could remember.
Before ask I spent a little time and after some tests I came up with theses solutions. They are examples but I cannot think about something better by now:
function queryHandlerOne(query: any) {
const fields = ["name", "featured", "price", "company", "rating"];
const entries = Object
.entries(query)
.filter(([key, _]) => fields.includes(key));
return Object.fromEntries(entries);
}
function queryHandlerTwo(query: any) {
const fields = ["name", "featured", "price", "company", "rating"];
const entries = Object
.keys(query)
.filter(key => fields.includes(key))
.reduce((acc, key) => {
acc[key] = query[key];
return acc;
}, {} as any);
return entries;
}
function queryHandlerThree(query: any) {
const fields = ["name", "featured", "price", "company", "rating"];
const result = Object
.keys(query)
.filter(key => fields.includes(key))
.map(key => [key, query[key]] as [string, any]);
return Object.fromEntries(result);
}
function queryHandlerFour(query: any) {
const fields = ["name", "featured", "price", "company", "rating"];
const result = {};
Object
.keys(query)
.filter(key => fields.includes(key))
.forEach(key => Object.assign(result, { [key]: query[key] }));
return result;
}