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?

分割代入を使ってオブジェクトから必要なプロパティだけを取り出す

Posted at

はじめに

  • axios のレスポンスは多くのプロパティを持つオブジェクトを返しますが、全てを使うわけではない(例: configheaders が不要なケース)

  • 実際に使うのは、datastatus などの一部のプロパティだけの場合が多い

  • 不要な部分を省いてコードを簡潔にし、読みやすくしたい

そこで、JavaScriptの分割代入(Destructuring Assignment) を使って不要な部分を省き、コードをシンプルに保つ方法を備忘録としてまとめました。

分割代入を使う理由

  • コードの簡潔化: 必要な部分だけにフォーカスできる。
  • 可読性の向上: 他の開発者がコードを見たとき、どのプロパティを使用しているかすぐに理解できる。
  • リネーム: プロパティの名前を変更して取り扱いやすくする。

実践例: 分割代入で必要なプロパティを抽出

1.こんなresponseが帰ってきていたとする:

qiita.rb

const response = {
  config: {
      adapter: (3) ['xhr', 'http', 'fetch'] 
      data: undefined
      env: {FormData: ƒ, Blob: ƒ}
  },
  data: ['Task 1', 'Task 2', 'Task 3'],                
  headers: { contentType: 'application/json' },
  request: XMLHttpRequest {
      status: 200,
      statusText: "OK"
  }
};

2.分割代入で必要なプロパティを抽出

qiita.rb
const { data, status } = response;

console.log(data);   // ['Task 1', 'Task 2', 'Task 3']
console.log(status); // 200

3. プロパティの名前を変更して取り出す

分割代入を使って、プロパティ名を変更することも可能です。

qiita.rb
const { data: tasks, status: httpStatus } = response;

console.log(tasks);      // ['Task 1', 'Task 2', 'Task 3']
console.log(httpStatus); // 200

参考

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?