Destructuring Assignment


Destructuring Assignment


The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Array and destructuring assignment


const arr = [1,2,3];
既存
const one = arr[0];
const two = arr[1];
const three = arr[2];
ES6 Destructuring Assignment

変数1対1対決

const [one,two,three] = arr;
console.log(one,two,three); //1,2,3

...rest

const [first,...rest] = arr;
console.log(first,rest); //1,[2,3]

Ignore values

const [, ,three] = arr;
console.log(three); //3

default value : set a default value in case the value in the array is undefined

const arr = [undefined, 'pizza', 'icecream'];
const [kfc = 'chicken', domino, baskin] = arr;
arr[0]==undefinedのため、この場合、「chicken」はデフォルト値として変数kfcに割り当てられる.

Object and destructuring assignment


const obj = {key1: 'number1', key2:'number2', key3:'number3'}
既存
const v1 = obj.key1;
const v2 = obj.key2;
const v3 = obj.key3;
ES6 Destructuring Assignment

変数1対1対決

const {key1, key2, key3} = obj;
カッコに割り当てる変数名としてオブジェクトのキーワードを使用する場合は問題ありませんが、オブジェクトのキーワードではなく変数名のみを使用する場合は、次のように変数がundefinedを返します.

したがって、次の形式(キーワード名:変数名)で記述する必要があります.

...rest

const {key1,...rest} = obj;
console.log(key1, rest); 
//'number1', {key2: 'number2', key3: 'number3'}

default value

const obj = {
  kfc: undefined,
  domino: 'pizza',
  starbucks: 'coffee'
}
console.log(obj.kfc); //undefined

const {kfc='chicken'} = obj;

console.log(kft); //'chicken'

Unpacking fields from objects passed as a function parameter

const user = {
  id: 42,
  displayName: 'jdoe',
  fullName: {
  firstName: 'John',
  lastName: 'Doe'
  }
};

function userId({id}) {
 	return id;
 }

 
function whois({displayName, fullName: {firstName: name}}) {
 	return `${displayName} is ${name}`;
 }
 
console.log(userId(user));
console.log(whois(user));