0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[JavaScript] 分割代入 (オブジェクト, 配列 → 新たな変数)_v2

Posted at

概要

分割代入(Destructuring Assignment) は、配列やオブジェクトから必要な値を「短く」「明示的に」「再利用しやすく」取り出す構文です。

つまり、

  • 配列やオブジェクトから値を取り出して、個別の変数に代入する
  • コードの可読性を上げる
  • 関数の引数処理やデータ抽出に便利

といった利点があります。

目次

基本構文

// オブジェクトの例
const options = {
  title: "Menu",
  width: 100,
  height: 200
};

// 通常のアクセス
console.log(options.title); // "Menu"

// 分割代入を使用
const { title, width, height } = options;
console.log(title); // "Menu"
console.log(width); // 100
console.log(height); // 200

オブジェクトから「必要な値だけを抜き出す」ことができます。

オブジェクトの分割代入

基本形

const user = { name: "Alice", age: 25 };
const { name, age } = user;

console.log(name); // "Alice"
console.log(age);  // 25

別名を付ける(エイリアス)

同じキー名の変数が他にある場合は、別名を付けられます。

const user = { name: "Alice", age: 25 };
const { name: userName, age: userAge } = user;

console.log(userName); // "Alice"
console.log(userAge);  // 25

デフォルト値を設定

値が存在しない場合の初期値を設定できます。

const user = { name: "Alice" };
const { name, age = 30 } = user;

console.log(age); // 30

ネストされたオブジェクト

const user = {
  name: "Alice",
  address: { city: "Tokyo", zip: "100-0001" }
};

const { address: { city } } = user;
console.log(city); // "Tokyo"

配列の分割代入

const arr = ["Alice", "Bob", "Charlie"];
const [first, second] = arr;

console.log(first);  // "Alice"
console.log(second); // "Bob"

要素のスキップ

const [,, third] = arr;
console.log(third); // "Charlie"

デフォルト値

const [a, b = "Default"] = ["Apple"];
console.log(a, b); // "Apple" "Default"

関数引数での分割代入

関数でオブジェクトを引数として受け取るときに便利です。

function showMenu({ title, width, height }) {
  console.log(`${title} (${width}×${height})`);
}

const options = { title: "Menu", width: 100, height: 200 };

showMenu(options);
// 出力: Menu (100×200)

関数の引数として受け取るプロパティ名が明確になり、保守性が向上します。

活用例: Object.entries と組み合わせる

Object.entries() はオブジェクトを [キー, 値] の配列に変換します。
これと分割代入を組み合わせると、非常に読みやすくなります。

let salaries = {
  "John": 100,
  "Pete": 300,
  "Mary": 250
};

function topSalary(salaries) {
  let max = 0;
  let maxName = null;

  for (let [name, salary] of Object.entries(salaries)) {
    if (max < salary) {
      max = salary;
      maxName = name;
    }
  }

  return maxName;
}

console.log(topSalary(salaries)); // Pete

🔍 解説

  • Object.entries(salaries)[["John", 100], ["Pete", 300], ["Mary", 250]]
  • for (let [name, salary] of ...) で各ペアを namesalary に展開
    entry[0]entry[1] と書かなくてよくなる

まとめ

対象 構文例 特徴
オブジェクト const { name, age } = obj プロパティ名で値を取り出す
配列 const [a, b] = arr 位置(インデックス)で値を取り出す
関数引数 function fn({key}){} 必要な値だけ抽出できる
ループで使用 for (let [key, val] of Object.entries(obj)) entry[0] / entry[1] の代わりに使える

参考リンク

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?