Repository navigation
Replies: 2 comments 3 replies
|
Your per-item parsing idea can be kept inside a schema, using import * as v from 'valibot';
function filterArray<TSchema extends v.GenericSchema>(itemSchema: TSchema) {
return v.pipe(
v.array(v.unknown()),
v.transform((items) => items.flatMap((item) => {
const result = v.safeParse(itemSchema, item);
return result.success ? [result.output] : [];
})),
);
}
const Schema = filterArray(v.object({
id: v.number(),
name: v.string(),
age: v.number(),
}));
const output = v.parse(Schema, input);
// Your example returns John, Jane, and Doe; 45 and "hello" are omitted.
type Output = v.InferOutput<typeof Schema>;
// { id: number; name: string; age: number }[]The outer This is for synchronous item schemas and intentionally discards their validation issues; an array with no valid items becomes |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Hi,
I have an array that contains lots of items of different schemas. I care only about a small subset of the schemas. So for example the following array:
I am only interested in the objects so I created the following schema:
But this fails with the following output:
How can I make this work by ignoring the other values?
All reactions