Replies: 2 comments
-
Hi! /**
* This function will remove the fields that are not valid according to the schema
* @template T
* @param {z.ZodType<T>} schema - The Zod schema to validate against.
* @param {z.ZodObject} object - The object to parse against the schema.
* @returns {Partial<T>} - The parsed and validated object with all fields optional.
*/
const parseSchemaObject = (schema, object) => {
try {
return schema.parse(object);
} catch (e) {
if (!(e instanceof z.ZodError))
throw new Error("Failed to parse object");
const errorFields = e.errors.map((err) => err.path[0]);
const fieldsToOmit = errorFields.reduce((obj, key) => {
obj[key] = object[key];
return obj;
}, {});
try {
return schema.omit(fieldsToOmit).parse(object);
} catch {
throw new Error("Failed to parse object");
}
}
}; Example of usage: import z from "zod";
const test = { name: "name", age: "invalid" };
const schema = z.object({
name: z.string(),
age: z.number(),
});
const parsed = parseSchemaObject(schema, test);
console.log(parsed); |
Beta Was this translation helpful? Give feedback.
0 replies
-
hi @rezaUniqe, what about this? z.object({
name: z.string(),
age: z.number().catch(undefined)
}) |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I am wondering how we can use Zod to parse an object and retrieve only the valid values while ignoring the invalid ones. For example, imagine having a JSON object:
Given the following Zod schema:
When I use
schema.validParse(test)
, I want to get an object with only the valid fields, like this:How can I achieve this?
Beta Was this translation helpful? Give feedback.
All reactions