온라인강의정리하기/JS
비구조화 할당
루체도
2021. 8. 18. 09:30
비구조화 할당이란?
객체 안에 있는 값을 추출해서 변수 혹은 상수로 바로 선언 해줄 수 있는 것.
또한 함수의 파라미터에도 비구조화 할당을 할 수 있다.
const test = { a : 1, b : 2 };
const {a , b} = test;
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)
함수에 전달을 할 때 object에 b값이 주어지지 않는다면 출력을 할 때 undefined가 나타나게 된다.
이런 상황에서 b 값에 기본 값을 주고 싶다면 c++에서 기본 값을 설정하듯이 하면 된다
function print({a, b = 2})
비구조화 할당 시 값 변경하기
const animal = {
name : '멍멍이',
type : '개'
};
const {name : nickname} = animal
console.log(nickname);
animal 객체 안에 있는 name을 nickname이라고 선언을 한다라는 의미.
배열 비구조화 할당하기
const array = [1, 2];
const [one, two] = array;
console.log(one);
console.log(two);
깊은 값 비구조화 할당
const deepObject = {
state: {
information: {
name: 'yoshi',
languages: ['korean', 'english']
}
},
value: 5
};
const { name, languages } = deepObject.state.information;
const { value } = deepObject;
const extracted = {
name,
languages,
value
};
console.log(extracted); // {name: "velopert", languages: Array[3], value: 5}
key이름으로 선언된 값이 존재하면 extracted에 바로 매칭을 시켜줘서 초기화가 된다.
이 문법은 ES6의 object-shorthand 문법
한 번에 안에 들어있는 값을 바로 추출하는 방법
const {
state : {
information : {name, languages}
},
value
} = deepObject