WEB/Java Script
[Java Script] 비구조화 할당(구조분해) 너무 어렵다!!!
자바칩 프라푸치노
2021. 4. 24. 01:22
const object = { a: 1, b: 2 };
const { a, b } = object;
console.log(a); // 1
console.log(b); // 2
객체에서 값을 꺼내주기 위해서 이렇게 사용한다.
비구조화 할당은 함수의 파라미터에서도 사용할 수 있다.
const object = { a: 1, b: 2 };
function print({ a, b }) {
console.log(a);
console.log(b);
}
print(object);
그런데 여기서b에 값이 없다고 가정해보겠다.
const object = { a: 1 };
function print({ a, b }) {
console.log(a);
console.log(b);
}
print(object);
// 1
// undefined
비구조화 할당시 기본값 설정
이러한 상황에 b에 기본값을 주려면 이렇게 하면 된다.
const object = { a: 1 };
function print({ a, b = 2 }) {
console.log(a);
console.log(b);
}
print(object);
// 1
// 2
비구조화 할당시 이름 바꾸기
이제부터 name을 nickname으로 부르고 싶다.
const animal = {
name: '멍멍이',
type: '개'
};
const nickname = animal.name;
console.log(nickname); // 멍멍이
그렇다고 기존에 animal이 가지고 있던 값이 바뀌는 것은 아니다.
배열 비구조화 할당
배열에서도 비구조화 할당을 할 수 있다.
const array = [1, 2];
const [one, two] = array;
console.log(one);
console.log(two);
배열에도 기본값을 정할 수 있다.
const array = [1];
const [one, two = 2] = array;
console.log(one);
console.log(two);
깊은 값 비구조화 할당
객체의 깊숙한 곳에 들어있는 값을 꺼내는 방법을 알아보자
const deepObject = {
state: {
information: {
name: 'velopert',
languages: ['korean', 'english', 'chinese']
}
},
value: 5
};
여기서 만약에 name이랑 languages랑 value를 꺼내고 싶다면?
const { name, languages } = deepObject.state.information;
const { value } = deepObject;
이렇게도 쓸 수 있다.
const extracted = {
name,
languages,
value
};
console.log(extracted); // {name: "velopert", languages: Array[3], value: 5}
const extracted = {
name: name,
languages: languages,
value: value
}
위 아래가 같은 코드이다.
만약에 key 이름으로 선언된 값이 존재하다면, 바로 매칭시켜주는 문법이다.
const {
state: {
information: { name, languages }
},
value
} = deepObject;
이렇게도 쓸 수 있다.
728x90