티스토리 뷰
디스트럭처링이란
- 객체 구조( structure )를 제거( de ) 한다는 의미가 있다.
- 디스트럭처링은 객체의 구조를 분해 후 할당이나 확장과 같은 연산을 수행한다.
자료형에 따라 다음과 같은 방식으로 나뉜다.
1. 객체 디스트럭처링
2. 배열 디스트럭처링
1. 객체 디스트럭처링
- 객체 리터럴에서 변수명에 대응하는 속성값을 추출해 변수로 할당하는데 유용하다.
이렇게 객체의 속성값을 변수에 할당하는 것을 디스트럭처링 할당이라고 한다.
let { id, name } = { id: 123, name:"gogo" };
console.log(id) // 123
console.log(name) // gogo
디스트럭처링 할당 표현식은 { id, name }과 같다.
디스트럭처링 할당 시 표현식 내부와 id와 name 변수는 객체의 속성값과 대응한다.
따라서 id에는 123 이 name에는 gogo가 할당된다.
* 새로운 변수 이름으로 할당
( 이것을 이해하지 못하면 하단부에 함수 매개변수 부분을 이해하기 힘들다 )
var o = {p: 42, q: true};
var {p: foo, q: bar} = o;
console.log(foo); // 42
console.log(bar); // true
*중첩된 객체의 구조 분해
var metadata = {
title: "Scratchpad",
translations: [
{
locale: "de",
localization_tags: [ ],
last_edit: "2014-04-14T08:43:37",
url: "/de/docs/Tools/Scratchpad",
title: "JavaScript-Umgebung"
}
],
url: "/en-US/docs/Tools/Scratchpad"
};
var { title: englishTitle, translations: [{ title: localeTitle }] } = metadata;
console.log(englishTitle); // "Scratchpad"
console.log(localeTitle); // "JavaScript-Umgebung"
* for of 반복문과 구조 분해
var people = [
{
name: "Mike Smith",
family: {
mother: "Jane Smith",
father: "Harry Smith",
sister: "Samantha Smith"
},
age: 35
},
{
name: "Tom Jones",
family: {
mother: "Norah Jones",
father: "Richard Jones",
brother: "Howard Jones"
},
age: 25
}
];
for (var {name: n, family: { father: f } } of people) {
console.log("Name: " + n + ", Father: " + f);
}
// "Name: Mike Smith, Father: Harry Smith"
// "Name: Tom Jones, Father: Richard Jones"
* 디스트럭처링 매개변수 선언
- 함수 호출시 객체 리터럴을 전달하고 객체의 리터럴 속성을 체크 ( undefined )하는 것은 꽤나 번거로운 일이다.
function profile( obj ){
var name="";
name=(obj.name !==undefined )? obj.name : "none" ;
}
profile( {name: "boy"} );
위 코드 내부를 보면 obj 객체의 속성에 name 속성이 있는지 검사하고 없다면 기본값으로 "none" 를 할당하고 있다면 객체의 속성을 할당하고 있다. 속성이 여러개라면 객체의 속성 검사를 위한 중복 코드가 발생하게 된다.
객체의 특정 속성 유무를 타입에서 검사하고 없다면 기본값을 할당할 수 있게 만들면 편리할 것이다.
아래와 같은 형식으로 디스트럭처링 매개변수를 선언할 수 있다.
function profile( { 매개변수1, 매개변수2, ... }){ ..중략...}
function profile( {name, job="?"}={name:"none"} ){
console.log( name ) // "gogo"
}
profile({name:"gogo"});
* 함수 매개변수로 전달된 객체로부터 분해하기
- 각 객체로부터속성들을 해체해 출력한다.
const checkItems = [
{ id: 1, check: true },
{ id: 2, check: false },
{ id: 3, check: false }
];
// checkItems 배열의 요소인 객체로부터 check 프로퍼티만을 추출하여 true인것을 리턴.
const checkItemView = checkItems.filter( ({ check }) => check );
console.log(checkItemView); // [ { id: 1, content: 'HTML', completed: true } ]
function userId({id}) {
return id;
}
function whois( {displayName: displayName, fullName: {firstName: name}} ){
console.log(displayName + " is " + name);
}
var user = {
id: 42,
displayName: "jdoe",
fullName: {
firstName: "John",
lastName: "Doe"
}
};
console.log("userId: " + userId(user)); // "userId: 42"
whois(user); // "jdoe is John"
참고 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
'Programming language > javascript' 카테고리의 다른 글
count rolling motion (0) | 2021.01.10 |
---|---|
code copy ( ctrl+c, ctrl+v 효과 ) (0) | 2021.01.10 |
count motion ( 숫자 랜덤 카운트 ) (0) | 2021.01.10 |
RxJs (0) | 2021.01.10 |
swiper ( 슬라이더 / 캐러셀 ) 라이브러리 (0) | 2021.01.08 |
- Total
- Today
- Yesterday
- 내장요소
- IntrinsicElements
- 리프래시토큰
- 태그
- git checkout -b
- CSS
- 반복문
- svg icon font
- 코도바
- interceptors
- svg 폰트
- 자바스크립트
- Vue3
- vue-router
- Intrinsic
- React.StrictMode
- icon font
- Angular
- react
- cordova
- svg모션
- 앵귤러
- Aptana
- JsDoc
- 아이콘 폰트 만들기
- anime.js
- RefreshToken
- git
- react-router-dom
- for of 구문
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |