PrismaP
Prisma2y ago
10 replies
Werdox

omit with condition

I want to only omit certain fields if a condition in the same thing I'm querying is true

example:
const channels = await prisma.channel.findMany({
   where: { ownerId: userId },
   omit: { name: /* Only omit 'name' if the channel type is 1 */ },
});
Solution
---
Here is the omitArray function for anyone finding this later
export function omitArray<Data extends object, Keys extends keyof Data>(
   data: Data[],
   keys: Keys[]
): Omit<Data, (typeof keys)[number]>[] {
   const result = [];

   for (const obj of [...data]) {
      const modifiedObj = { ...obj };
      for (const key of keys) {
         delete modifiedObj[key];
      }

      result.push(modifiedObj);
   }

   return result;
}
Was this page helpful?