Skip to content

get keys from object shape #2134

Answered by navtoj
navtoj asked this question in Q&A
Feb 27, 2023 · 7 comments · 15 replies
Discussion options

You must be logged in to vote

you could make a recursive function that would get the keys from schema.shape

// get zod object keys recursively
const zodKeys = <T extends z.ZodTypeAny>(schema: T): string[] => {
	// make sure schema is not null or undefined
	if (schema === null || schema === undefined) return [];
	// check if schema is nullable or optional
	if (schema instanceof z.ZodNullable || schema instanceof z.ZodOptional) return zodKeys(schema.unwrap());
	// check if schema is an array
	if (schema instanceof z.ZodArray) return zodKeys(schema.element);
	// check if schema is an object
	if (schema instanceof z.ZodObject) {
		// get key/value pairs from schema
		const entries = Object.entries(schema.shape);
		// lo…

Replies: 7 comments 15 replies

Comment options

You must be logged in to vote
4 replies
@kimmobrunfeldt
Comment options

@navtoj
Comment options

@kimmobrunfeldt
Comment options

@kimmobrunfeldt
Comment options

Comment options

You must be logged in to vote
6 replies
@ozzyfromspace
Comment options

@krisgrm
Comment options

@ptim
Comment options

@McKayMower
Comment options

@DaleMcNair
Comment options

Answer selected by navtoj
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
2 replies
@vgjenks
Comment options

@Oguntoye
Comment options

Comment options

You must be logged in to vote
3 replies
@schalkventer
Comment options

@gunhaxxor
Comment options

@janvorwerk
Comment options

Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
Converted from issue

This discussion was converted from issue #2114 on March 03, 2023 15:22.