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?

テンプレートリテラルでオブジェクトの中身が表示されない

1
Posted at

はじめに

デバッグ時にconsole.logで値を確認する場面は多いと思います。複数の値を出力するとき、説明用の文字列と変数を一緒に表示したくなります。
テンプレートリテラルを使えば、+で結合せずにプレースホルダ ${}で変数を埋め込めます。

const a = 5;
const b = 10;

// + で結合
console.log('a + b = ' + (a + b));

// テンプレートリテラル
console.log(`a + b = ${a + b}`);

// どちらも "a + b = 15"と出力される

しかし、非同期で取得したResponseオブジェクトをテンプレートリテラルで出力しようとしたところ、中身が表示されず [object Response] となってしまいました。今回は、オブジェクトを console.log() で表示する際の注意点をまとめます。

テンプレートリテラルとは
バッククォート(`)で囲む文字列の書き方で、以下の特徴があります。

  • ${}で変数や式を埋め込める
  • 改行をそのまま含められる
  • +で結合するより読みやすい

原因

テンプレートリテラル内でオブジェクトを埋め込むと、JavaScriptは内部でtoString()メソッドを呼び出します。ResponseオブジェクトのtoString()[object Response]という文字列を返すため、中身が見えません。

const response = await fetch('http://localhost:3000/api/sample/123');
// オブジェクトの中身が見えない
console.log(`response: ${response}`);
// "response: [object Response]" と表示される

解決方法

console.log()にオブジェクトを直接引数として渡すと、オブジェクトが展開されて表示されます。

const response = await fetch('http://localhost:3000/api/sample/123');

// オブジェクトを直接渡す
console.log('response:', response);
// Response { status: 200, statusText: 'OK', ... }

// 個別のプロパティを確認する
console.log('response status:', response.status);
console.log('response ok:', response.ok);
// response status: 200
// response ok: true

// JSONデータを取得してから出力
const data = await response.json();
console.log('data:', data);
// data: { id: 'user123', email: 'test@example.com' }

// 見やすく整形する場合
console.log(`response: ${JSON.stringify(data, null, 2)}`);
// response: {
//   "id": "123",
//   "email": "test@example.com"
// }

Responseオブジェクトの主なメソッド

  • response.json() → JSONとして解析
  • response.text() → テキストとして取得
  • response.blob() → バイナリデータとして取得
  • response.arrayBuffer() → ArrayBufferとして取得

さいごに

console.log でテンプレートリテラルを使う際、オブジェクトがtoString()で文字列化されることを知りませんでした。オブジェクトの中身を確認したいときは、カンマ区切りで直接渡すのがシンプルですね。

参考サイト

テンプレートリテラル
オブジェクトのログ出力

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?