티스토리 뷰

반응형

ES6부터 구조분해 할당(destructuring assignment)이라는 문법이 등장했다. 말 그대로 어떤 배열이나 객체를 분해한 후 다시 할당하는 것이다. ES5와 ES6를 비교하며 알아보자.

 

 

 

 

 

 

 

 

 

 

 

 

1. 배열 구조분해 할당

1) 형식

ES5

배열의 모든 요소에 접근해 하나씩 변수에 담는 방식이다.

 

1
2
3
4
5
6
const fruits = ['apple''banana''kiwi'];
const red = fruits[0];
const yellow = fruits[1];
const green = fruits[2];
 
console.log(red, yellow, green); // apple banana kiwi
cs

 

 

ES6

fruits 배열을 해체하여 배열 요소 순서와 선언된 변수의 순서에 맞게 그 값을 각각 할당한다. 코드를 훨씬 더 간단하게 작성할 수 있다.

 

1
2
3
4
5
6
7
const fruits = ['apple''banana''kiwi'];
const [red, yellow, green] = fruits;
 
console.log(red, yellow, green); // apple banana kiwi
console.log(red); // apple
console.log(yellow); // banana
console.log(green); // kiwi
cs

 

비어있는 곳은 값이 할당되지 않으며, 기존 배열 요소 개수가 더 적어서 변수에 할당할 값이 없는 경우 디폴트 값을 설정할 수 있다.

 

1
2
3
4
const fruits = ['apple''banana''kiwi'];
const [a, , c, d = "empty"= fruits;
 
console.log(a, c, d); // apple kiwi empty
cs

 

 

2) '...' 연산자 사용하여 나머지 배열 할당

배열의 남은 부분을 하나의 변수에 한 번에 담을 수도 있다.

 

1
2
3
4
5
6
const array = [12345678910];
const [first, second, ...trash] = array;
 
console.log(first); // 1
console.log(second); // 2
console.log(trash); // [3, 4, 5, 6, 7, 8, 9, 10]
cs

 

 

3) 배열 합치기

'...' 연산자를 사용하여 배열을 펼친 다음 하나로 합친다.

 

1
2
3
4
5
6
const array1 = [12345];
const array2 = [678910];
const array3 = [...array1, ...array2];
 
console.log(...array2, ...array1); // 6 7 8 9 10 1 2 3 4 5
console.log(array3); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
cs

 

 

 

 

 

 

2. 객체 구조분해 할당

1) 형식

배열 구조분해 할당 형식과 비슷하다. 값이 없는 경우 출력되는 디폴드 값을 정할 수 있다. key 값이 맞다면 그 key 값에 맞는 데이터가 출력된다.

 

1
2
3
4
5
6
7
8
9
const user = {
    id: 'aa',
    name'Kim',
    age: 38,
}
const {id, name, age, gender = "None"= user;
 
console.log(id, name, age, gender); // aa Kim 38 None
console.log(age, name, id, gender); // 38 Kim aa None (순서가 변경되어도 key 값이 맞으면 key 값에 맞게 출력됨)
cs

 

 

2) '...' 연산자 사용하여 나머지 객체 할당

 

1
2
3
4
5
6
7
8
9
const user = {
    id: 'aa',
    name'Kim',
    age: 38,
}
const {id, ...rest} = user;
 
console.log(id); // aa
console.log(rest); // {name: 'Kim', age: 38}
cs

 

 

 

3) 객체 합치기

'...' 연산자를 사용하면 하나의 객체로 합쳐지고, 사용하지 않으면 객체를 통째로 가져와 합쳐진다.

 

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
29
30
31
32
const user = {
    id: 'aa',
    name'Kim',
    age: 38,
}
const user_grade = {
    test1: 99,
    test2: 89,
    test3: 100,
}
const user_etc = {
    nationality: 'KOREA',
    gender: 'w',
}
 
const user_info = {...user, ...user_etc, user_grade}
 
console.log(user_info);
/*
{
    age: 38
    gender: "w"
    id: "aa"
    name: "Kim"
    nationality: "KOREA"
    user_grade: {
        test1: 99
        test2: 89
        test3: 100
    }
}
*/
cs

 

 

 

3) 중첩 객체 구조분해 할당

 

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
29
30
31
32
33
34
35
36
const obj = {
    a: '안녕하세요',
    b: {
        c: '반갑습니다',
        d: {
            e: '안녕히가세요',
        },
    },
}
 
const {
    a,
    b: {
        c,
        d: {
            e,
        },
    },
= obj;
 
console.log(a); // 안녕하세요
console.log(b);
/*
{
    c: '반갑습니다',
    d: {
        e: '안녕히가세요',
    },
}, 
*/
 
console.log(c); // 반갑습니다
 
console.log(d); // {e: '안녕히가세요'}
 
console.log(e); // 안녕히가세요
cs

 

 

 

 

3. 구조분해 할당 응용

 

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
const shop = [
    {
        "name""happy flower",
        "homepageURL""www.happy-flower555.com",
        "description" : [
            "Lorem ipsum dolor sit,",
            "amet consectetur adipisicing elit.",
            "Blanditiis, architecto veniam.",
        ],
    },
    {
        "name""modern interior",
        "homepageURL""www.modern-interior123.com",
        "description": [
            "Adipisci, ipsa harum, sint veniam eveniet obcaecati iste,",
            "quis impedit eos rem provident excepturi temporibus at maiores",
            "repellat asperiores esse inventore quas?",
        ],
    },
];
 
 
// shop의 두 번째 요소 출력
const [,modern] = shop;
console.log(modern);
/*
{
    "name": "modern interior",
    "homepageURL": "www.modern-interior123.com",
    "description": [
        "Adipisci, ipsa harum, sint veniam eveniet obcaecati iste,",
        "quis impedit eos rem provident excepturi temporibus at maiores",
        "repellat asperiores esse inventore quas?",
    ],
}
*/
 
 
 
// 위에서 출력한 modern 객체에서 name과 homepageURL 출력
const {name, homepageURL} = modern;
console.log(name, homepageURL); // modern interior www.modern-interior123.com
 
 
 
// 위 두 단계를 한 번에 출력
const [,{name, homepageURL}] = shop;
console.log(name, homepageURL); // modern interior www.modern-interior123.com
 
 
cs

 

 

 

 

반응형
반응형
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
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 29 30 31