I'm absolutly stuck trying to dynamically add object methods in a for loop to an already existing object/class.
I want to dynamically add the order method for every object existing in the contactsSorter array from within a for loop.
I've tried it with forEach, with setting the query = variable in the for loop and without. Making it to a function and looked for similar cases but wasn't able to fix the issue that it seems to overwrite the query in the for loop.
import { createClient } from '@supabase/supabase-js'
// Create a single supabase client for interacting with your database
const supabase = createClient(
'https://xyzcompany.supabase.co',
'public-anon-key'
)
// Initialize array to loop over
const contactsSorter = [
{
order: "ascend",
field: "first_name",
columnKey: "first_name",
},
{
order: "ascend",
field: "created_at",
columnKey: "created_at",
},
];
// Initialize variable i want to modify in for loop
let query = supabase.from("contacts").select("*", { count: "exact" });
if (contactsSorter.length > 0) {
// Here I want to dynamically add the order by clause to the query
for (let i = 0; i < contactsSorter.length; i++) {
query = query.order(contactsSorter[i].field, {
ascending: contactsSorter[i].order === "ascend" ? true : false,
});
}
} else {
query = query.order("first_name", {
ascending: true,
});
}
let { data: contacts, error, count } = await query;