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

More than 5 years have passed since last update.

オブジェクトと配列のでストラクチャーリング JavaScript (ES6, ES2015)

Last updated at Posted at 2018-05-15

Destructuring (分割代入)

日本語難しいので、デストラクチャーリング って横文字で読んでます。、
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

1. オブジェクトのデストラクチャーリング(Object Destructuring)

今までのデータをこう読み込んでいたのが・・・

data.js
var user = {
  name: 'Ayako Sayama',
  age: 16,
  location: 'Vancouver',
}

var name = user.name;
var age = user.age;
var location = user.location;

こうやって読み込むことができるようになりましたー。

data.js
var user = {
  name: 'Ayako Sayama',
  age: 16,
  location: 'Vancouver',
}
const { name, age, location } = user;

2. 配列のデストラクチャーリング(Array Destructuring)

配列も上記のオブジェクトと一緒です。
{} が []に変わるだけ。

data.js
var user = [
  'Ayako Sayama', 'Vancouver', 'Megane'
];

var name = user[0]; // 'Ayako Sayama'
var age = user[1]; // 'Vancouver'
var location = [2]; // 'Megane'

data.js
var user = [
  'Ayako Sayama', 'Vancouver', 'Megane'
];
const [ name, age, location ] = user;
console.log(name); // 'Ayako Sayama'

ここでは、デストラクチャーリングする時に、好きな変数に置き換えることができます。(name="Ayako Sayama")

3. 関数のパラメーターをでストラクチャーリング(Destructuring in function parameters)

Before

パラメーターの中身もわからないし、順番も正確じゃないといけないので面倒!

fetchData.js
function fetchData(language, name, age, nationality, hasBoyfriend) {
  ...
}

fetchData("Japanese", "Ayako", 10, "Japanese", true);

After

fetchData.js
function fetchData({ language, name, age, hasBoyfriend, nationality }){
  ...
}

fetchData({
  language: 'Japanese',
  name: 'Ayako Sayama',
  hasBoyfriend: true,
  nationality: 'Japanese',
  age: 16,
});

順番はバラバラでOK!

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