[JS] 비구조화 할당

Minyoung's Conference·2022년 5월 14일
0

JavaScript

목록 보기
7/28
post-thumbnail

비구조화 할당은 객체, 배열안의 값을 추출해서 변수, 상수에 바로 선언하는 문법 이다.

const obj = { a: 1, b: 2 };

const a = obj.a;
const b = obj.b;
console.log(a); // 1
console.log(b); // 2

위와 같이 객체를 a,b를 선언해줄 수 있지만, 양이 많아지면 비효율적이게 된다.
그래서 비구조화 할당을 사용한다.

const obj = { a: 1, b: 2 };

const { a, b } = obj;

console.log(a); // 1
console.log(b); // 2

객체 안의 값을 쉽게 상수나 변수에 할당해주는 문법이다. 뿐만 아니라,
배열에서도 사용가능하다.

const arr = [1, 2];

const [a, b] = arr;

console.log(a); // 1
console.log(b); // 2

//다른 예제로 더 단순하게 만들어보자.

let [one, two, three] = ["one", "two", "three"];
console.log(one, two, three); // one two three

만약 값이 존재하지 않는다면 undefined로 뜨게 된다. 하지만 undefined를 원하지 않는다면 기본값을 정해줄 수 있다.

let [one, two, three, four] = ["one", "two", "three"];
console.log(one, two, three, four); 
// one two three undefined

쉽지만 중요한 예제를 한 번 같이 보자.

let a = 10;
let b = 20;

[a, b] = [b, a];
console.log(a, b);
// 20 10

위 예제는 비구조화할당을 이용해 a,b의 값을 손쉽게 swap한 경우이다.
왼쪽의 값에 오른쪽값을 넣어주는 것이기 때문에,
a에 b(=20)의 값을, b에 a(=10)의 값을 넣어준다고 이해해야 한다.

이번엔 세 개의 프로퍼티를 가지는 객체를 만들어보자.

let object = { one: "one", two: "two", three: "three"};

let one = object["one"];
let two = object.two;
let three = object.three;

console.log(one, two, three); // one two three

위도 반복노동이 존재한다. 비구조화 할당을 이용해보자.

let object = { one: "one", two: "two", three: "three"};

let {one, two, three} = object;
console.log(one, two, three); // one two three

객체의 비구조화 할당은 배열의 index를 이용하는 게 아니라, key값을 기준으로 이용한다.

let object = { one: "one", two: "two", three: "three", name: "bradley"}

let {name, one, two, three} = object;
console.log(one, two, three, name); // one two three bradley

순서는 상관없다. key값이 기준이다.

또한, key값의 변화도 가능하다.

let object = { one: "one", two: "two", three: "three", name: "bradley"}

let {name: myName, one:oneOne, two, three} = object;
console.log(oneOne, two, three, myName); // one two three bradley

마찬가지로, undefined를 제거하기 위한 기본값도 넣어줄 수 있다.

let object = { one: "one", two: "two", three: "three", name: "bradley"}

let {name: myName, one:oneOne, two, three, abc="four"} = object;
console.log(oneOne, two, three, myName, abc); // one two three bradley four

비구조화 할당을 이용해 손쉽게 서버의 데이터를 받아올 수 있다.

profile
안녕하세요, FE 개발자 김민영입니다.

0개의 댓글