DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

2

Zod - TypeScript-first schema declaration and validation library #11

Image description

Transform Data from Within a Schema

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

We are going back to our Star Wars example:

import { z } from 'zod';

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

const StarWarsPeopleResults = z.object({
  results: z.array(StarWarsPerson),
})

export const fetchStarWarsPeople = async () => {
  const data = await fetch(
    'https://www.totaltypescript.com/swapi/people.json',
  ).then((res) => res.json());

  const parsedData = StarWarsPeopleResults.parse(data);

  return parsedData.results;
}
Enter fullscreen mode Exit fullscreen mode

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 to StarWarsPerson itself.

We need to take our base StarWarsPerson and add a transformation that will split the names on space to give us a nameAsArray

👉 Solution:

Here is what StarWarsPerson looked like before the transformation:

const StarWarsPerson = z.object({
  name: z.string(),
})
Enter fullscreen mode Exit fullscreen mode

When we parse the name in .object(), we are going to take the person we receive and transform it to add additional properties:

const StarWarsPerson = z
  .object({
    name: z.string(),
  })
  .transform((person) => ({
    ...person,
    nameAsArray: person.name.split(' '),
  }))
Enter fullscreen mode Exit fullscreen mode

Inside of the .transform(), person is the object from above that includes the name.

This is also where we add the nameAsArray property that satisfies the test.

This occurs at the StarWarsPerson level instead of inside the fetch function or elsewhere.


I hope you found it useful. Thanks for reading. 🙏
Let's get connected! You can find me on:

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay