Destructuring을 활용하여 자바스크립트에서 중첩된 객체 필터링하기

자바스크립트에서 객체를 다룰 때, 특정 조건에 맞는 요소들만 추출하고 싶을 때가 있습니다. 이를 위해 Destructuring을 사용하여 중첩된 객체를 필터링하는 방법을 알아보겠습니다.

객체 필터링하기

다음은 중첩된 객체에서 특정 조건에 맞는 요소들을 필터링하는 예제입니다.

const data = {
  id: 1,
  name: "John Doe",
  email: "johndoe@example.com",
  address: {
    street: "123 Main St",
    city: "New York",
    zip: "10001"
  },
  orders: [
    { id: 1, product: "Apple", quantity: 3 },
    { id: 2, product: "Banana", quantity: 5 },
    { id: 3, product: "Orange", quantity: 2 }
  ]
};

const { name, address: { city }, orders } = data;
const filteredOrders = orders.filter(order => order.quantity > 3);

console.log(name); // "John Doe"
console.log(city); // "New York"
console.log(filteredOrders); 

위 예제에서는 data 객체에서 name, city, orders를 필터링하여 추출하였습니다. namecity는 중첩된 객체의 속성을 추출하여 변수에 할당한 것이고, orders는 배열이므로 filter 메소드를 사용하여 quantity가 3보다 큰 요소들만 추출하였습니다.

결론

Destructuring을 활용하여 자바스크립트에서 중첩된 객체를 필터링하는 방법에 대해 알아보았습니다. 이를 활용하여 필요한 데이터만 추출하여 효과적으로 다룰 수 있습니다. Destructuring은 코드를 간결하고 가독성 있게 만들어주는 강력한 기능이므로, 앞으로 자바스크립트에서 객체를 다루게 될 때 유용하게 활용해보세요.

#javascript #destructuring #객체필터링