Object Destructuring: Extracting Object Properties
Understand the differences between extracting object data in a traditional way and using object destructuring with the help of examples.
Enhanced object literals, which you saw earlier in the chapter, provide a nice way to create an object using values from variables in lexical scope. Object destructuring is the opposite; it provides an elegant way to extract data from objects into variables in local or lexical scope.
Traditional way to extract object data
Let’s extract the data from an object using the hard way first and then see how object destructuring helps. Suppose we have an object that holds a person’s details.
'use strict';//START:OBJECTconst 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:OLDconst firstName = sam.name;const theAge = sam.age;//END:OLDconsole.log(`${firstName} ${theAge}`);
Now, let’s examine the code to extract the values for the properties. If we want to get only some of the properties, we can use the old techniques; see line 18 and ...