Javascript - Destructuring Nesting Object

Introduction

The destructuring syntax can be nested to retrieve information.

If the values you're destructuring have nested objects or arrays, you can destructure those nested values as well.

let items = { 
    count : 2, 
    name: "fruits", 
    XML: { 
        quantity: 5, 
        value: 25 
    }, 
    Keyboard: { 
        quantity: 3, 
        value: 5 
    } 
}; 

let { XML: { quantity }} = items; 

console.log(quantity);        // 5 

Consider the following example:

let { XML: {} } = items; 
console.log(XML);      // ReferenceError: XML is not defined 

To create binding for the variable XML, use = to define a default value rather than : that defines a location, for example:

let { XML = {} } = items; 
console.log(XML);      // {quantity: 5, value: 25} 

You can insert another array pattern into the overall pattern and the destructuring will descend into a nested array:

let fruits = [ "XML", [ "blueberry", "raspberry" ], "Keyboard" ]; 

let [ fruit1, [ fruit2 ], fruit4 ] = fruits; 

console.log(fruit1);       // "XML" 
console.log(fruit2);       // "blueberry" 
console.log(fruit4);       // "Keyboard" 

The extra square brackets in the destructuring statement around fruit2 are required to unpack the fruits array and the berries array present inside it.

The following code shows a longer object literal destructuring.

Demo

let student = { 
    name: "Tony", 
    courses: { //from   w w w .j  av  a 2s .  c o  m
        english: { 
            id: 1, 
            score: 7 
        }, 

        math: { 
            id: 2, 
            score: 9 
        } 
    }, 
    scoreRange: [0, 10] 
}; 

let { 
    courses: { english }, 
    scoreRange: [ minScore ] 
} = student; 

console.log(english.id);        // 1 
console.log(english.score);     // 7 
console.log(minScore);          // 0

Result

Related Topic