본문 바로가기
STUDY/JavaScript

[JavaScript] JSON(5) 구조분해

by bottlesun 2022. 11. 27.
728x90

01. JSON에 대한 구조분해할당 (=비구조할당)

구조 분해 할당 구문은 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 JavaScript 표현식이다.

object 에는 {} 안에 명시된 항목과 동일한 key를 갖는 데이터가 존재해야한다.

let obj = {num: 123, boolean: true};
let {num, boolean} = obj;
console.log(num); // 42
console.log(boolean); // true

01-1. 구조분해를 활용하여 필요한 데이터만 추출하기

객체 안에 들어있지 않은 값을 입력하면, undefined 이 출력 된다.

const data = {name:'hello' , age : 20 , height:172,weight:85};
const {name} = data;
console.log(name);
// hello
console.log(data.height)
// 172

01-2. 객체 안 key 구조분해 후 이름 변경하기

이름을 변경 하더라도, 원본 data 값이 변하지는 않는다.

//data 안에 height 와 weight를 분해하면서 이름을 h와 w로 변경
const data = {name:'hello' , age : 20 , height:172,weight:85};
const {name} = data;
const {height : h , weight : w} = data;
console.log(h,w);
//172 85
console.log(data);
// { name: 'hello', age: 20, height: 172, weight: 85 }

01-3. 구조분해를 수행한 나머지를 별도로 분리하기

a1, a2를 제외 한 나머지는 ...list 값에 다 들어가게 된다.

const dummy = {a1 : 100, a2:200 , a3:300, a4:400};
const {a1,a2,...list} = dummy;
console.log(a1,a2); // 100 , 200
console.log(list); // { a3: 300, a4: 400 }

02. 배열에 대한 구조분해

02-1. 기본사용

//기본 사용
const array = [1,2];
const [one , two] = array;
console.log(one); // 1
console.log(two); // 2

02-2. 구조분해 별도 분리하기

// 구조분해를 수행한 나머지를 별도로 분리하기
[b1,b2,...list] =  [1,2,3,4,5,6,7,8,9];
console.log(b1); //1
console.log(b2); //2
console.log(list); //[나머지]
728x90

댓글