LoginSignup
0
0

More than 3 years have passed since last update.

Object destructuring / Javascript

Last updated at Posted at 2020-04-21

オブジェクトから値を取り出す方法

例えばJavascriptのオブジェクトから値を取り出すときどのように取り出しますか。

const product = {
  destination: 'hawaii',
  price: 59800,
  stock: 20
}

私は今まで以下のようにしていました。

const dst = product.destination
const price  = product.price

これでも問題なく出力されます。

console.log(dst, price)
>> hawaii 59800

ショートハンド

再定義するのが冗長な感じがするので、以下のようなショートハンドで記載可能です。
destinationにdstを割り当てる

const { destination: dst, price } = product

同じ結果が得られます。

console.log(dst, price)
>> hawaii 59800

順を追って書き直すとイメージしやすいです。

// 1. {}という変数にproductオブジェクトを定義
const {} = product
// 2. 
const { destination, price } = product

console.log(destination, price)
>> hawaii 59800
// 3. 新しい変数への割り当て
const { destination: dst, price } = product

console.log(destination, price)
>> エラー "ReferenceError: destination is not defined ~~~"

console.log(dst, price)
>> hawaii 59800

プロパティの追加

また、既存のオブジェクトにないプロパティの追加も可能です。

const { destination: dst, price, rating } = product

このままだとエラーが出ます。

console.log(dst, price, rating)
>> hawaii 59800 undefined

ratingに5という値を入れてみましょう

const { destination: dst, price, rating = 5 } = product
console.log(dst, price, rating)
>> hawaii 59800 5

ratingが表示されました。

関数の引数として取り出す

const addHotel = (hotel, myProduct) => {
  const { destination: dst, price } = myProduct; 
  console.log(hotel, dst, price)
}

addHotel('yhrm Hotel', product)

>> yhrm Hotel hawaii 59800

または、引数に直接記載します。

const addHotel = (hotel, { destination: dst, price }) => {
  console.log(hotel, dst, price)
}

addHotel('yhrm Hotel', product)

>> yhrm Hotel hawaii 59800

まとめ

整理すると

  1. ショートハンドとして書ける
  2. 新しい変数名の割り当てができる
  3. 既存のオブジェクトにないプロパティを追加できる

参考

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