0
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?

【Web】オブジェクト構造のJSONをリストへ変換する方法

Posted at

はじめに

今年に入ってWebの開発を進めています。
Next.js+TypeScriptの組み合わせで実装を行なっていますが、そんな中でAPIを叩いて取得したデータに関しリストでの返却を期待していたところ、まさかのオブジェクトとしてそれz独立した構造で返ってくるという問題が発生しました。
そこでオブジェクト構造で返却されたJSONデータを扱いやすいリストへと受け取った側で変換する方法を備忘録的にまとめておこうと思います。

リスト化の方法

まず、以下のようなJSONが帰ってくるとします。

sample.json
{
	"tests": {
		"test1": {
			"name": "テスト"
		},
        "test2": {
			"name": "テスト"
		}
        "test3": {
			"name": "テスト"
		}
        "test4": {
			"name": "テスト"
		}
	}
}

本来であればtestsはリスト構造で返却されればベストなのですが、API的な都合などでリスト的な返却が難しい場合、受け取った側で扱いやすいようリスト化する必要があります。

上記レスポンスをリスト化するためには以下のように実装することで実現可能です。

page.tsx
type TestData = {
  name: string;
};

type ApiResponse = {
  tests: Record<string, TestData>;
};

const parseTests = (data: ApiResponse): TestData[] => {
  return Object.values(data.tests);
};

// APIから取得したデータ(仮)
const apiResponse: ApiResponse = {
  tests: {
    test1: { name: "テスト" },
    test2: { name: "テスト" },
    test3: { name: "テスト" },
    test4: { name: "テスト" }
  }
};

// tests を配列化
const testArray = parseTests(apiResponse);

console.log(testArray);

実装のポイント

  1. Record<string, TestData> を使用
    tests のキー(test1, test2 など)は 動的に増減 する可能性がある為、
    Record<string, TestData> を使用することで、任意のキー名を持つオブジェクトを表現可能です。

  2. Object.values() を使って配列化
    Object.values(data.tests) を使うと、testsのすべての値(TestData)だけを配列に変換可能です。

  3. 型安全にデータを扱える
    ApiResponse 型を定義することで、API のレスポンス構造が変わったときに型エラーで気付くことが可能です。

以上になります。

さいごに

Web側はJSONを扱いやすくて便利ですね。

0
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
0
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?