JavaScript 分割代入

ECMAScript 2015 (ES2015 / ES6)では分割代入が使えます。

今回は分割代入についてご紹介します。

配列の分割代入

分割代入は以下のように使います。

const [a, b] = [100, 200]

console.log(a) //100
console.log(b) //200

スプレッド構文(…)を使うことで others は 100 と 200 を除いた配列になります。

const [a, b, ...others] = [100, 200, 300, 400, 500]

console.log(a) //100
console.log(b) //200
console.log(others) //[300, 400, 500]

100 と 200 と 400 のみを代入したい場合は以下のようにします。

const [a, b,, d] = [100, 200, 300, 400, 500]

console.log(a) //100
console.log(b) //200
console.log(d) //400

初期値をセットすることも可能です。

const [a, b, c = 999] = [100, 200]

console.log(a) //100
console.log(b) //200
console.log(c) //999

応用ですが配列の先頭とそれ以外を代入ということも可能です。

const [head, ...tail] = [100, 200, 300, 400]

console.log(head) //100
console.log(tail) //[200, 300, 400]

変数の入れ替えも簡潔にかけます。

let a = 1;
let b = 2;

[a, b] = [b, a]

console.log(a) //2
console.log(b) //1

オブジェクトの分割代入

オブジェクトで分割代入する場合は、プロパティー名を指定します。

配列のときと似たことができます。

const { hoge, foo, buu = 999, ...others} = {hoge: 100, foo:200, x: 100, y: 200}

console.log(hoge) //100
console.log(foo) //200
console.log(buu) //999
console.log(others) // {x: 100, y: 200}

変数名を変更することも可能です。以下はプロパティーaの値をaaという変数に代入しています。

const {a: aa} = {a: 'aaa', b: 'bbb'}

console.log(aa) //aaa

ネストされたオブジェクトの代入も可能です。

const user = {
  name: 'tami',
  age: 33,
  description: {
    fruit: 'orange',
    color: 'green',
  }
}

const {name, age, description: {fruit, color}} = user

console.log(name) //tami
console.log(age) //33
console.log(fruit) //Orange
console.log(color) //green

ちなみに以下のように()で囲んだ場合も、const で定義した場合と同じです。

({a, b, c = 999} = {a: 100, b: 200})

console.log(a) //100
console.log(b) //200
console.log(c) //999

配列とオブジェクトの分割代入を組み合わせた使い方も可能です。

// ageの大きい順に並んだオブジェクト配列
const data = [
  {name: 'taro', age: 90},
  {name: 'jiro', age: 88},
  {name: 'saburo', age: 70},
  {name: 'kiyoshi', age: 66},
]

const [{age: maxAge}] = data

console.log(maxAge) //90