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

JavaScript/オブジェクトでの分割代入

Posted at

オブジェクトの分割代入

分割代入とは…
オブジェクトや配列から特定のプロパティや要素を簡単に取り出すための構文

分割代入を使う場合と使わない場合の比較

分割代入を使わずにオブジェクトのプロパティを取り出す場合

const menu = {
  isSetMenu: true,
  mainMenu: {
    mainName: 'Cheeseburger',
    topping: 'cheese',
  },
  sideMenu: 'french fries',
  drink: 'cola',
  setPrice: 8.5,
};

const isSetMenu = menu.isSetMenu;
const mainName = menu.mainMenu.mainName;
const topping = menu.mainMenu.topping;
const sideMenu = menu.sideMenu;
const drink =menu.drink;
const setPrice = menu.price;

console.log(mainName);  //Cheeseburger
console.log(setPrice);  //8.5

分割代入を使ってオブジェクトのプロパティを取り出す場合

const menu = {
  isSetMenu: true,
  mainMenu: {
    mainName: 'Cheeseburger',
    topping: 'cheese',
  },
  sideMenu: 'french fries',
  drink: 'cola',
  setPrice: 8.5,
};

const {
  isSetMenu,
  mainMenu: {
    mainName,
    topping,
  },
  sideMenu,
  drink,
  setPrice,
} = menu;

console.log(mainName);  //Cheeseburger
console.log(setPrice);  //8.5

分割代入の便利な機能

const menu = {
  isSetMenu: true,
  mainMenu: {
    mainName: 'Cheeseburger',
    topping: 'cheese',
  },
  sideMenu: 'french fries',
  drink: 'cola',
  setPrice: 8.5,
};

const {
  isSetMenu,
  mainMenu: {
    mainName: burger,  //変数名を"burger"と指定
    topping,
  },
  // sideMenuは取り出さない
  drink,
  addMenu = 'onion rings',  //未定義のプロパティにデフォルト値を設定
  ...others  //残余プロパティを取得
} = menu;

console.log(isSetMenu);  //true
console.log(burger);  //Cheeseburger
console.log(topping);  //cheese
console.log(addMenu);  //onion rings
console.log(others);  //{setPrice: 8.5, sideMenu: "french fries"}

分割代入を関数の引数としての使用

const menu = {
  isSetMenu: true,
  mainMenu: {
    mainName: 'Cheeseburger',
    topping: 'cheese',
  },
  sideMenu: 'french fries',
  drink: 'cola',
  setPrice: 8.5,
};

const printMenu = ({
  isSetMenu,
  mainMenu: {
    mainName: burger,
    topping,
  },
  drink,
  addMenu = 'onion rings',
  ...others
}) => {
  console.log(isSetMenu,burger,topping,drink,addMenu,others);
};

printMenu(menu);
//true 'Cheeseburger' 'cheese' 'cola' 'onion rings' {sideMenu: 'french fries', setPrice: 8.5}

参考記事

分割代入 - JavaScript - MDN Web Docs - Mozilla

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