ㅇㅇㅈ Blog

프론트엔드 수행중

0%

JS-구조 분해 할당

JS-Destructuring-assignment

구조 분해 할당


객체데이터의 구조분해할당

  • 어떤 객체데이터에서 구조 분해 해서 원하는 속성들만 꺼내서 사용할 수 있는 개념
  • 데이터.속성 으로 표기하는 점표기법과 동일하다
  • 데이터[‘속성’] 인덱싱 방법과도 같다
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const user = {
name: 'abc',
age: 85,
email: 'abc@gmail.com',
}

const { name, age, email, address } = user

console.log(`사용자의 이름은 ${name}입니다.`)
// 사용자의 이름은 abc입니다.
console.log(`사용자의 이름은 ${age}입니다.`)
// 사용자의 이름은 85입니다.
console.log(address)
// undefined

const { name, age, email, address = 'korea' } = user
// 기본값을 지정해줄 수 있다.
1
2
3
4
5
6
7
8
9
10
const user = {
name: 'abc',
age: 85,
email: 'abc@gmail.com'
address: 'usa'
}

const { name, age, email, address = 'korea' } = user
console.log(address)
// usa 출력

구조분해 할때 기본값을 지정했어도 데이터 안에 값이 있으면 데이터의 값으로 출력 된다

객체데이터의 속성의 이름을 바꿀때

1
2
3
4
5
6
7
8
9
10
11
12
const user = {
name: 'abc',
age: 85,
email: 'abc@gmail.com',
}

const { name: hello, age, email, address } = user
console.log(hello)
// abc 출력된다

console.log(name)
// name is not defined 에러가 출력된다

배열데이터의 구조분해할당

  • { }가 아닌 [ ]기호를 사용 해야 한다
  • 객체데이터와는 다르게 인덱싱되어 있기 때문에 이름이 아닌 순서대로 추출해야 한다
1
2
3
4
const fruits = ['Apple', 'Banana', 'Cherry']
const [a, b, c, d] = fruits
console.log(a, b, c, d)
// Apple Banana Cherry undefined 출력된다

중간에 있는 데이터를 추출하고 싶을때

  • 필요없는 값은 비어두고 쉼표(,)로 순서를 구분해 주기만 하면 된다
1
2
3
4
const fruits = ['Apple', 'Banana', 'Cherry']
const [, b] = fruits
console.log(b)
// Banana 가 출력된다

전개 연산자 (Spread)

  • 배열데이터를 쉼표(,)로 구분되는 각각의 아이템으로 전개해서 출력한다.
1
2
3
4
5
const fruits = ['Apple', 'Banana', 'Cherry']
console.log(fruits)
// ['Apple', 'Banana', 'Cherry'] 배열이 출력된다
console.log(...fruits)
// 'Apple' 'Banana' 'Cherry' 문자열로 출력된다
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const fruits = ['Apple', 'Banana', 'Cherry']
function toObject(a, b, c) {
return {
a: a,
b: b,
c: c,
}
}
console.log(toObject(...fruits))
// {a: 'Apple', b: 'Banana', c: 'Cherry'}
console.log(toObject(fruits[0], fruits[1], fruits[2]))
// 전개 연산자로 작성한것과 같은 방법..

console.log(toObject(fruits))
// {a: Array(3), b: undefined, c: undefined}
// a에 배열자체가 들어가 버린다

fruits의 아이템들이 toObject의 인수로 들어가 객체데이터의 형태로 출력된다


1
2
3
4
5
6
7
8
9
10
const fruits = ['Apple', 'Banana', 'Cherry', 'Orange']
function toObject(a, b, ...c) {
return {
a: a,
b: b,
c: c,
}
}
console.log(toObject(...fruits))
// {a: 'Apple', b: 'Banana', c: Array(2)} 출력된다

매개변수에서 사용할때는 순서대로 받아보고 순서가 명확하지 않을때는
나머지를 배열의 형태로 다 받는다