1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Zod】パース後にデータを変換する方法

Last updated at Posted at 2024-03-24

パース後にデータを変換するにはtransformを使用します。
以下に使用例を示します。

数値を文字列に変換

import { z } from 'zod';

// 数値から文字列への変換
const numberToString = z.number().transform(num => num.toString());

// バリデーションと変換
const result = numberToString.parse(123); // "123"

オブジェクトのプロパティを変換

import { z } from 'zod';

// オブジェクトスキーマの定義
const originalSchema = z.object({
  name: z.string(),
  age: z.number(),
});

// ageプロパティを文字列に変換する新しいスキーマ
const transformedSchema = originalSchema.transform(obj => ({
  ...obj,
  age: obj.age.toString(),
}));

// バリデーションと変換
const result = transformedSchema.parse({ name: 'John', age: 30 }); // { name: 'John', age: '30' }

オブジェクトのキーをキャメルケースに変換

import { z } from 'zod';

function toCamelCase(str: string): string {
  return str.replace(/([-_][a-z])/g, group => group.toUpperCase()
                                              .replace('-', '')
                                              .replace('_', ''));
}

const originalSchema = z.object({
  first_name: z.string(),
  last_name: z.string(),
});

const transformedSchema = originalSchema.transform(obj => {
  const newObj: any = {};
  for (const key in obj) {
    newObj[toCamelCase(key)] = obj[key];
  }
  return newObj;
});

const result = transformedSchema.parse({ first_name: 'John', last_name: 'Doe' });
// result: { firstName: 'John', lastName: 'Doe' }
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?