Array filtering May filter out items in array which does not match zod schema JSON.parse validation After JSON.parse() validation with zod we get truly typed data
const sortModelSchema = z.array(
z.object({
colId: z.string(),
sort: z.enum(['asc', 'desc']),
}),
)
const {
success: parseSortModelSuccess,
error: parseSortModelError,
data: parsedSortModel,
} = sortModelSchema.safeParse(JSON.parse(sortModel))
if (parseSortModelSuccess === false) {
throw new Error('Invalid sortModel format', parseSortModelError)
}
const sort = parsedSortModel.reduce<Record<string, 1 | -1>>(
(accumulator, item) => {
if (item.sort === 'asc') {
accumulator[item.colId] = 1
}
if (item.sort === 'desc') {
accumulator[item.colId] = -1
}
return accumulator
},
{},
)