Zod Tutorial (10 exercises)

Transform Data from Within a Schema

Another useful feature of Zod is manipulating data from an API response after parsing.

To see this in action, we're going back to our Star Wars example.

Recall that we created StarWarsPeopleResults with a results array of StarWarsPerson schemas.

When we get the name of a StarWarsPerson from the API, it's their full name.

What we want to do is add a transformation on StarWarsPerson itself


Your challenge is to take our base StarWarsPerson and add a transformation that will split the names on space to give us a nameAsArray.

The test shows what you're looking for:

This one's a bit more challenging, so check out the transform docs for some examples.


We're going back to our fetch example for a minute here because we want to be able to do something interesting, which is, we want to take the base StarWarsPerson that we've got here, and then what we're going to do is fetch all of these people. We actually want to do some manipulation of the data after we've parsed it.

What we need here and what our tests are expecting, is that the first thing that comes out of this StarWarsPeople thing is going to be Luke Skywalker, and the name is already Luke Skywalker. If we refactor this slightly, let's say, const results equals this, and just grab this, and we're going to say, expect results to equal this.

Our tests are still going to fail in the same way, but it means that we can just console.log (results). What that's going to do is going to show us all of the data that's coming back here. What we're getting is Luke Skywalker, C-3PO, etc. We're getting a similar result to what we got earlier, which is the results are the z.array(StarWarsPerson).

We want to find a way on StarWarsPerson itself, transform it, so we can add a new property which is named as array which is the name split with the space here. This is a more challenging one, but it's such a cool and useful pattern that I couldn't help but include it.