Mixed Array and Object Destructuring
What You'll Learn: How to combine array and object destructuring in a single expression to extract values from complex, nested data structures.
The Core Idea
Real-world data rarely comes in a single, flat format. You'll often encounter arrays containing objects, objects containing arrays, or even deeper nesting. JavaScript lets you destructure both patterns simultaneously in one expression, letting you dig straight to the values you need without intermediate variables.
Think of it like unpacking a delivery box (array) that contains labeled compartments (objects) — you can open the box and reach into specific compartments all in one motion.
Basic Mixed Destructuring
When an array contains objects:
const users = [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 }
];
// Destructure first array element AND its properties
const [{ name, age }] = users;
console.log(name); // 'Alice'
console.log(age); // 30
When an object contains arrays:
const response = {
status: 'success',
data: [10, 20, 30]
};
// Destructure object property AND array elements
const { status, data: [first, second] } = response;
console.log(status); // 'success'
console.log(first); // 10
console.log(second); // 20
Deep Nesting
You can go deeper:
const apiResponse = {
results: [
{ id: 1, scores: [85, 90, 88] }
]
};
const { results: [{ scores: [first] }] } = apiResponse;
console.log(first); // 85
This extracts the first score from the first result in one line.
Key Takeaway: Mixed destructuring lets you combine [] and {} patterns to reach deeply nested values directly, making your code more concise when working with complex data structures.