Structuring, Object Destructuring

이재진·2021년 3월 21일
0
post-thumbnail

Structuring

해당 코드는 효율적이지 않다.
human 객체의 name 과 새로 선언한 변수의 이름이 같다.
바로 밑의 lastName도 마찬가지.

효율적이지 못한 코드를 Structuring을 통해 간단히 바꿔 줄수 있다.

const {}  

-> 이것은 객체 안에 있는 property들을 가져오는 것을 의미 한다.

const {} = human;

-> 그리고 그것이 어떤 객체인지를 가르쳐 준다. 이런식으로

const {name, lastName} = human;

->human이라는 객체로 가서 name의 값을 새로운 변수인 name에 넣는 것과 같다.

const name = human.name;  
const {name} = human;


정상적으로 출력된다.


Object Destructuring

다른 방법으로

const nationality = human.nationality;  
const {nationality} = human;

human 객체의 nationality라는 property를 값을 가져오고 싶은데 해당 이름(nationality라는)을 사용하고 싶지않다면

const newNation = human.nationality;  // 첫번째는 새로운 변수에 할당해주는 방법
//const newNation = human.nationality;  
const {nationality: newNation} = human; 

-> {nationality: newNation}= human 의 뜻은 human이라는 객체로 가서 nationality라는 변수 값을 가져오고 그 값을 newNation에 넣어주라는 뜻.


-> 새로운 변수에 할당 하는 기존 방법도 가능하지만 Object Destructuring을 통한 방법도 가능하다. newNation으로 콘솔에 찍어도 잘 나온다.

중괄호 {} 안에 무언가를 넣는다는 거는 그 해당 객체 안으로 들어가라는 것이다.

profile
개발블로그

0개의 댓글