Zod Section 10 exercises

Transform Data from Within a Schema

As a reminder, here's what StarWarsPerson looked like before the transformation:

const StarWarsPerson = z.object({
name: z.string()

Adding the Transformation

When we parse the name in .object(), we're going to take the person we receive and transform it to add addit

Loading solution


Matt Pocock: 0:00 The big change we've made here is we've started using the transform API from Zod, which is super duper cool. What it does is it says when we parse this name, what we're going to do is take that person that we receive and then transform it. We can add new properties to it.

0:19 What we've got here is nameAsArray: person.name.split("-"). What this is doing is it's taking the name property that we parse here. Then, it's splitting it by space. What we end up with is an array of those persons' names. What we get...I'm just console.logging it down here, in the same way I did before.

0:39 We end up with an array of name 'Luke Skywalker' and nameAsArray 'Luke' "Skywalker'. It doesn't work for C-3P0 but it does work for Darth Vader, Leia Organa, Owen Lars, etc. I don't know who Owen Lars is.

0:52 This transform API, you can see it's actually working just at the StarWarsPerson level. This doesn't just work for objects. It can actually work for arrays, too, or work for any Zod primative. We can transform this and we can say...We've got the name. Let's just say we go Awesome and ${name}.

1:13 What this is going to do now is this is going to prepend Awesome onto all of the results. We've got Awesome Biggs Darklighter. Awesome Beru Whitesun Lars. Who are these people?

1:23 You get the idea. Transform is an incredibly useful API because it acts at the lowest level and allows you to...You can obviously do multiple transforms, as well, if you really want. It's an incredibly cool API.