관리 메뉴

웹개발자의 기지개

[Javascript] 비구조화 할당(Destructuring Assignment) 본문

javascript

[Javascript] 비구조화 할당(Destructuring Assignment)

웹개발자 워니 2025. 10. 13. 10:50

 

1) 배열 비구조화 할당

 

const arr = [10, 20, 30];

// 기존
const a = arr[0];
const b = arr[1];

// 비구조화
const [x, y] = arr;   // x=10, y=20

 

 

일부만 받기 / 건너뛰기

const [first, , third] = [10, 20, 30]; // first=10, third=30

 

기본값 주기 (값이 undefined일 때만 적용)

const [a = 1, b = 2] = [100]; // a=100, b=2

 

나머지 요소 모으기 (rest)

const [head, ...tail] = [1,2,3,4]; // head=1, tail=[2,3,4]

 

값 바꾸기(스왑) 한 줄 요령

let left = 'L', right = 'R';
[left, right] = [right, left]; // left='R', right='L'

 

 

2) 객체 비구조화 할당
객체는 키 이름이 중요해요. 같은 이름의 변수로 꺼냅니다.

 

const user = { name: 'Lee', age: 20 };

// 기존
const name1 = user.name;
const age1 = user.age;

// 비구조화
const { name, age } = user; // name='Lee', age=20

 

 

변수명 바꾸기(별칭/리네이밍)
(오른쪽 키가 name, 왼쪽 변수는 username)

 

 

const { name: username } = { name: 'Lee' }; // username='Lee'

 

 

기본값 주기

 

const { nick = '익명' } = {};           // nick='익명'  (undefined일 때만)
const { x = 0 } = { x: null };          // x=null (기본값 적용 안 됨: null은 undefined가 아님)

 

 

중첩 객체 꺼내기

const post = {
  id: 1,
  author: { id: 10, name: 'Jane' }
};

const {
  author: { name: authorName }
} = post;
// authorName='Jane'
// 주의: 이렇게 꺼내면 author라는 변수는 생기지 않아요(바로 내부 name만 꺼냄)

 

나머지 속성 모으기 (rest)

const { id, ...info } = { id: 1, title: 'Hello', views: 7 };
// id=1, info={ title:'Hello', views:7 }

 

 

3) 함수 파라미터에서의 비구조화 (React에서 최강 활용)
(1) props 받기

 

function Button({ size = 'md', color = 'blue', onClick, ...rest }) {
  // size, color, onClick만 바로 꺼내씀 + 나머지는 rest에
  return <button onClick={onClick} {...rest}>Click</button>;
}

 

장점: props.size처럼 매번 점(.) 찍지 않아도 되고, 기본값을 같이 선언할 수 있어요.

 

 

(2) useState 튜플 해체

const [count, setCount] = useState(0);
// 배열 비구조화: 첫 번째는 값, 두 번째는 setter 함수

 

 

(3) 이벤트 객체에서 필요한 값만 뽑기

function Input() {
  const onChange = (e) => {
    const { target: { name, value } } = e; // 중첩 비구조화
    console.log(name, value);
  };
  return <input name="email" onChange={onChange} />;
}

 

 

(4) API 응답에서 필요한 필드만

const res = await fetch('/api/user');
const data = await res.json();
// data = { id, name, profile: { avatar, bio }, ... }
const { name, profile: { avatar } } = data;

 

 

4) 자주 하는 실수와 팁

1. 배열 vs 객체 기준

배열: 순서가 일치해야 함

객체: 키 이름이 일치해야 함

2. 기본값은 undefined일 때만
null이나 ''(빈 문자열), 0일 때는 기본값이 적용되지 않아요.

3. 이미 선언된 변수에 객체 비구조화 할당 시 괄호 필요

let a;
// ({ a } = { a: 10 });  // ← 괄호로 감싸야 구문 에러 방지

 

 

4. 깊은 중첩 시 가독성
너무 중첩되면 먼저 변수로 분리하거나, 옵션 체이닝(?.)과 함께 단계적으로 접근을 권장:

 

const authorName = post?.author?.name ?? 'Unknown';

 

 

5) React 스타일 실전 미니 예제

 

function ProfileCard(props) {
  // 1) props 비구조화
  const {
    user: {
      name,
      email,
      avatarUrl = '/images/default.png', // 기본값
    },
    onFollow,
    ...restProps // 나머지 전달
  } = props;

  return (
    <div {...restProps}>
      <img src={avatarUrl} alt={`${name} avatar`} />
      <h3>{name}</h3>
      <p>{email}</p>
      <button onClick={onFollow}>Follow</button>
    </div>
  );
}

// 사용
<ProfileCard
  user={{ name: 'Lee', email: 'lee@example.com' }}
  onFollow={() => console.log('follow')}
  className="card"
/>

 

 

 

const [a=1, b=2, c=3] = [10, undefined, null];
console.log(a, b, c);

 

정답: 10 2 null (b만 기본값 적용)

 

 

const user = { name: 'Kim', addr: { city: 'Seoul', zip: '00000' } };

 

정답 : const { addr: { city: myCity } } = user;

 

 

function onChange(e) { /* 여기 작성 */ }

 

정답 : 

function onChange(e) {
  const { target: { value, checked } } = e;
}

 

 

필요한 상황(React 컴포넌트, 훅, 이벤트, API 응답)에서 “점 연타” 대신 깔끔하게 꺼내 쓰는 기술이 바로 비구조화 할당이다.

 

Comments