자바스크립트 '구조 분해 할당' [Destructuring]

프린이·2025년 5월 16일

🎯구조 분해 할당( ES6 )❓

배열이나 객체의 속성을 해체하여
그 값을 개별 변수에 담을 수 있게 하는 JS 표현식❗

let obj = {
  accessory: 'horn',
  animal: 'horse',
  color: 'purple',
  hairType: 'curly'
}function buildAnimal(animalData) {
  let accessory = animalData.accessory,
      animal = animalData.animal,
      color = animalData.color,
      hairType = animalData.hairType;
  ...
} // 위에 객체에 접근하려면 이렇게 해야함,,,😬

👇

✨구조 분해 할당 사용

function buildAnimal(animalData) {
  let {accessory, animal, color, hairType} = animalData;
  ...
}  // 이렇게 하면 훨씬 간결해짐

🌊깊게 들어간 '객체 구조 분해 할당'

객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게

let person = {
  name: 'Maya',
  age: 30,
  phone: '123',
  address: {
    zipcode: 1234,
    street: 'rainbow',
    number: 42
  }
}
👇
// 구조 분해 할당
let {address: {zipcode, street, number}} = person;
console.log(zipcode, street, number); // 1234 rainbow 42

구조 분해 할당❌➡person.address.zipcode 접근 해야하지만
구조 분해 할당⭕➡'개별 변수'로 가져와서 하면 됨

🎈배열 구조 분해 할당

✅ 생략 가능( , 이걸로 순서는 나타내줘야함 )😎

const numbers = [1, 2, 3, 4, 5, 6];
const [,,three,,five] = numbers;

✅ 다른 이름 변수명 사용

firstName 이름이 길다 싶으면 fName 처럼 저렇게 작성해도 무관

지금은 값이 있지만 할당된게 없을 때 'not given'이 기본 값이 되는 것

🔹 사용 사례

var people = [
  {
    name: "Mike Smith",
    family: {
      mother: "Jane Smith",
      father: "Harry Smith",
      sister: "Samantha Smith"
    },
    age: 35
  },
  {
    name: "Tom Jones",
    family: {
      mother: "Norah Jones",
      father: "Richard Jones",
      brother: "Howard Jones"
    },
    age: 25
  }
];

// name이라는 이름을 n으로 사용하겠다는 것
for (var {name: n, family: { father: f } } of people) {
  console.log("Name:  " + n + ", Father: " + f);
}

// "Name: Mike Smith, Father: Harry Smith"
// "Name: Tom Jones, Father: Richard Jones"
profile
안녕하세요! 퍼블리싱 & 프론트엔드 개발 공부 블로그 입니다!

0개의 댓글