Search⌘ K
AI Features

Object Destructuring: Deep Destructuring, and Collisions

Explore deep object destructuring techniques in JavaScript to extract nested properties and learn how to manage name collisions by assigning unique variable names. Understand how to destructure into existing variables by using parentheses to avoid syntax errors, enhancing your ability to write clean and precise code.

Deep destructuring

In the previous lessons on object destructuring, we extracted the top-level properties of objects. The destructuring syntax makes it easy to extract properties in lower levels and even embedded objects.

Let’s extract the street property of the address embedded object in sam.

Javascript (babel-node)
'use strict';
//START:OBJECT
const weight = 'WeightKG';
const sam = {
name: 'Sam',
age: 2,
height: 110,
address: { street: '404 Missing St.'},
shipping: { street: '500 NoName St.'},
[weight]: 15,
[Symbol.for('favoriteColor')]: 'Orange',
};
//END:OBJECT
//START:NESTED
const { name, address: { street } } = sam;
//END:NESTED
console.log(street);
try {
console.log(address);
} catch(ex) {
console.log(ex.message);
}

As you have seen, the name property, which is a top-level property, is extracted. In addition, the street property, which is nested within the address property is extracted. Use caution: this syntax defines only two variables, name and street. It does not define the ...