21일차[배열 & 객체 구조 분해 / 실습 예제]

진하의 메모장·2025년 2월 5일
2

공부일기

목록 보기
27/66
post-thumbnail

2025 / 02 / 05

오늘은 배열과 객체의 구조 분해(Destructuring)에 대해 배웠습니다.
단어 보고 이게 뭔가 싶었는데 코드를 작성할 때 사용하고 있던 부분이었습니다.
오늘 포스팅에서는 구조 분해(Destructuring)에 대해 다루겠습니다.



💌 구조 분해 (Destructuring)

자바스크립트에서 구조 분해는 배열이나 객체의 값을 쉽게 변수에 할당할 수 있도록 도와주는 문법입니다. 코드가 더욱 간결하고 직관적으로 변할 수 있습니다.



💌 배열의 구조 분해

배열에서 구조 분해를 사용하면, 배열의 요소를 변수에 쉽게 할당할 수 있습니다.


1) 배열 구조 분해

  • 배열은 배열의 인덱스를 하나하나 지정해 값을 할당할 수 있습니다.
const arr = [1, 2, 3];

let num1 = arr[0];
let num2 = arr[1];
let num3 = arr[2];

console.log(num1, num2, num3);  // 출력: 1 2 3
  • 구조 분해를 사용하면 아래와 같이 간결하게 작성할 수 있습니다.
const [num4, num5, num6] = arr;

console.log(num4, num5, num6);  // 출력: 1 2 3


2) 중간값 건너뛰기

  • 배열에서 중간값을 건너뛰고 특정 값만 할당할 수 있습니다.
  • 쉼표( , )를 이용해 건너뛰고 싶은 값을 생략할 수 있습니다.
const arr2 = [10, 20, 30];
const [x, , y] = arr2;

console.log(x, y);  // 출력: 10 30


3) 기본값 설정

  • 배열에 값이 없을 때, 기본값을 설정하여 undefined를 방지할 수 있습니다.
  • second는 배열에 값이 없으므로 기본값 100이 할당됩니다.
const numbers = [42];

const [first, second = 100] = numbers;

console.log(first, second);  // 출력: 42 100


4) 나머지 요소 배열로 받기

  • 배열에서 구조 분해를 하면 처음 몇 개의 값은 개별 변수에 할당하고, 나머지 값들은 하나의 배열로 받을 수 있습니다.
  • ...rest는 나머지 값을 모두 배열로 받습니다.
const arr3 = [1, 2, 3, 4, 5, 6, 7, 8];

const [numFirst, numSecond, ...rest] = arr3;

console.log(numFirst, numSecond);  // 출력: 1 2
console.log(rest);  // 출력: [3, 4, 5, 6, 7, 8]


💌 객체의 구조 분해

객체에서 구조 분해를 사용할 때는, 객체의 키를 변수에 할당할 수 있습니다.


1) 객체 구조 분해

  • 객체의 키와 변수의 이름이 일치하면 바로 값을 할당할 수 있습니다.
const user = {
    name: "이한",
    age: 22
};

const { name, age } = user;

console.log(name, age);  // 출력: 이한 22


2) 변수 이름 바꾸기

  • 객체의 키와 변수 이름이 다를 경우, :을 사용하여 변수 이름을 변경할 수 있습니다.
  • name은 Fullname으로, age는 newAge라는 이름으로 변수에 할당됩니다.
const user2 = {
    name: "태산",
    age: 22
};

const { name: Fullname, age: newAge } = user2;

console.log(Fullname, newAge);  // 출력: 태산 22


3) 나머지 속성 받기

  • 객체에서 나머지 속성을 받을 때는 ...을 사용합니다.
  • restInfo는 나머지 속성들을 객체로 받습니다.
const idol = {
    group: "Boynextdoor",
    debut: "2023",
    member: 6,
    company: "KOZE"
};

const { group, debut, ...restInfo } = idol;

console.log(group, debut);  // 출력: Boynextdoor 2023
console.log(restInfo);      // 출력: { member: 6, company: 'KOZE' }


4) 매개변수에서 구조 분해

  • 함수의 매개변수로 객체를 전달받을 때, 바로 구조 분해를 사용할 수 있습니다.
  • 함수에 객체를 전달하면서, 객체의 속성들을 매개변수에서 바로 구조 분해할 수 있습니다.
function showIdol({ group, debut, member, company }) {
    console.log(`${group}, ${debut}, ${member}, ${company}`);
}

const idol = {
    group: "Boynextdoor",
    debut: "2023",
    member: 6,
    company: "KOZE"
};

showIdol(idol);  // 출력: Boynextdoor, 2023, 6, KOZE


💌 추가적인 예시

객체와 배열을 함께 사용하는 경우

  • 배열 안에 객체가 있는 경우, 객체와 배열을 모두 구조 분해할 수 있습니다.
const arr = [
    { name: "진하", age: 21 },
    { name: "연히", age: 22 }
];

const [
    { name: firstName, age: firstAge },
    { name: secondName, age: secondAge }
] = arr;

console.log(firstName, firstAge);   // 출력: 진하 21
console.log(secondName, secondAge); // 출력: 연히 22

기본값과 결합

  • 배열과 객체에서 기본값을 설정하고 결합하여 사용할 수도 있습니다.
  • user 객체에 age 속성이 없으면 기본값인 22이 할당됩니다.
const user = { name: "예히" };

const { name, age = 22 } = user;

console.log(name, age);  // 출력: 예히 22


💌 실습 예제(1)

도서 목록 출력하기

  • 객체 생성 (title (책 제목), author (저자), year (출판 연도) 속성을 가집니다.)
  • 제목만 다르고 저자와 출판연도가 같은 Book객체를 복사하여 새로운 객체를 만듭니다.
  • 메서드를 만들어 "책 제목 - 저자 (출판 연도)" 형태의 문자열을 반환합니다.
  • ibrary 객체를 생성합니다.(books 배열을 속성으로 가집니다.)
  • book 객체를 추가하는 메서드를 작성합니다.
  • 현재 도서목록을 출력하는 메서드를 작성합니다.

1) 객체 생성

객체 생성 (title (책 제목), author (저자), year (출판 연도) 속성을 가집니다.)

  • 해당 값에는 임의로 값을 넣어줍니다.
let book = {
    title: "book1",
    author: "OOO",
    year: 2003,
};


2) 새로운 객체 생성

제목만 다르고 저자와 출판연도가 같은 Book객체를 복사하여 새로운 객체를 만듭니다.

  • 스프레드 오퍼레이터를 사용해 객체의 값을 복사합니다.
  • 그 후 넣어주고 싶은 title의 값을 따로 입력해줍니다.
let book2 = {
    ...book,
    title: "book2",
};


3) 출력 메서드 생성

메서드를 만들어 "책 제목 - 저자 (출판 연도)" 형태의 문자열을 반환합니다.

  • 만들어둔 book 객체 안에 출력을 할 수 있는 메서드를 익명함수의 형태로 만들어줍니다.
let book = {
    title: "book1",
    author: "OOO",
    year: 2003,
    write: function() {
        return `${this.title} - ${this.author} (${this.year})`;
    }
};


4) 객체 생성

ibrary 객체를 생성합니다.(books 배열을 속성으로 가집니다.)

  • ibrary 객체안에 books라는 빈 배열을 생성합니다.
let Library = {
    books: [],
};


5) 추가 메서드 생성

book 객체를 추가하는 메서드를 작성합니다.

  • 함수의 매개변수로 info의 값을 받아오고 해당 내용을 Library라는 객체 안의 Books라는 배열에 Push하여 값을 넣습니다.
  • 함수를 호출할 때 적어주는 인수 값이 매개변수의 자리로 넘겨 받고 해당 값을 info로 사용하는 구조로 이루어져 있습니다.
let Library = {
    books: [],
    add: function(info) {
        this.books.push(info);
    },
};


6) 출력 함수 생성

map( ) & join( )사용

show: function() {
	return this.books.map(item => item.write()).join("\n");
},

forEach( ) 사용

show1: function() {
	this.books.forEach((book, index) => {
	console.log(`${index + 1}. ${book.write()}`);
});


💌 전체 코드

  • 위의 코드를 하나로 합쳐놓은 것입니다.
let book = {
    title: "book1",
    author: "OOO",
    year: 2003,
    write: function() {
        return `${this.title} - ${this.author} (${this.year})`;
    }
};

let book2 = {
    ...book,
    title: "book2",
};

let Library = {
    books: [],
    add: function(info) {
        this.books.push(info);
    },

    show: function() {
        return this.books.map(item => item.write()).join("\n");
    },

    show1: function() {
        this.books.forEach((book, index) => {
            console.log(`${index + 1}. ${book.write()}`);
        });
    }
};

Library.add(book);
Library.add(book2);

console.log(Library.show());
Library.show1();


💌 실습 예제(2)

1. 첫번째와 세번째 요소를 구조분해하여 변수에 저장하세요

const numbers = [10, 20, 30, 40];
const [num1, , num3, ] = numbers;
console.log(num1, num3); // 10, 30


2. 첫번째 요소는 firstColor, 나머지 요소는 otherColors로 구조분해 하세요.

const colors = ["red", "blue", "green", "yellow"];
const [firstColor, ...otherColors] = colors;
console.log(firstColor);
console.log(otherColors);


3. 다음 객체를 구조분해하여 변수에 할당하세요.

const person = { name: "Alice", age: 25, city: "Seoul" };
const {name, age, city} = person;
console.log(name, age, city);


4. 다음 객체의 기본값을 지정하여 year에 값을 할당하세요.

const car = { brand: "Tesla", model: "Model 3" };
const { brand, year = 2 } = car;
console.log(brand, year);


5. 함수의 매개변수를 구조분해 하세요.

const book = { title: "JavaScript Guide", author: "John Doe", year: 2021 };
function printBookInfo({title, author}) {
  console.log(`Title: ${title}, Author: ${author}`);
}
printBookInfo(book);


💌 실습 예제(3)

api 데이터 추출하기

  • api데이터에서 username과 email을 추출하세요.
const apiResponse = {
	status: 200,
	data: {
		user: {
			id: 42,
			username: "devCoder",
			profile: {
				email: "dev@example.com",
				phone: "123-456-7890"
        	}
		}
    }
};
const { data: { user: { username, profile: { email } } } } = apiResponse;
  
console.log(username); 
console.log(email);    



21일차 후기

  • 구조 분해라는 정확한 명칭을 알고 사용해본건 이번이 처음입니다.
  • 항상 그냥 무의식적으로 사용해봤지 정확한 명칭을 알려고 한적이 없었네요.
  • 그래도 이번 기회에 확실히 정리하고 넘어갈 수 있어서 다행인 것 같습니다.
  • 실습 예제를 푸는데 보통 모든 데이터가 이런 형식이라고.. 중첩된 객체에서 값을 가져오는게 어려울 것 같아서 속으로는 고민을 정말 많이 했습니다.
  • 근데 생각보다 간단하게 해결되는 것을 보고 조금 허무했습니다. (。・ω・。)?
profile
૮꒰ ྀི〃´꒳`〃꒱ა

0개의 댓글