LoginSignup
27
18

More than 3 years have passed since last update.

【JavaScript】分割代入はネストできる

Posted at

分割代入 (Destructuring) は下のように配列やオブジェクトを分解して代入することができる。

const [x, y] = [1, 2, 3]
// x = 1, y = 2

const {a, b, c} = {a: 1, b: 2}
// a = 1, b = 2, c = undefined

さらに destructuring は下のようにネストできる。

const [[x, y], [z, w]] = [[3, 2, 5], [4]]
// x = 3, y = 2, z = 4, w = undefined

const {a: {a1, a2}, b: {b1}} = {a: {a1: 1}, b: {}}
// a1 = 1, a2 = undefined, b1: undefined

オブジェクトと配列を組み合わせることもできる。

const [{x, y}, [z, w]] = [{x: 1}, [2, 3]]
// x = 1, y = undefined, z = 2, w = 3

エラーと回避

以下の場合エラーが発生するので注意する必要がある。

  • undefinednull が オブジェクトとして destructure されるとき
  • iterable1 でない値が配列として destructure されるとき
// プロパティ a の値 undefined がオブジェクトとして destructure されている
const {a: {b}} = {}  // Uncaught TypeError: Cannot destructure property `b` of 'undefined' or 'null'.

// 2番目の要素 5 が配列として destructure されている
const [a, [b, c]] = [3, 5]  // Uncaught TypeError: undefined is not a function

上記のケースのうち、「存在しない要素/プロパティを destructure するとき」と「undefined を destructure するとき」に発生するエラーはデフォルト値 {} [] を指定することで回避できる

const {a: {b} = {}} = {}
// b: undefined

const [a, [b, c] = []] = [3]
// a = 3, b = undefined, c = undefined

これは API の JSON レスポンスなどから値を取り出すときに非常に便利である。

Twitterの例
const {
  user: {
    name,
    entities: {
      url: {
        urls = []
      } = {}
    } = {}
  } = {}
} = tweetObject

  1. iterable とは簡単に言えば値を一つづつ取り出せるオブジェクトのことで、配列や Set などがこれにあたる。詳細はMDN。 

27
18
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
27
18