Book of Coding


Extract values from arrays and objects

Using destructurings (destructuring applications), it is possible to assign values that are stored in object properties or arrays to different variables relatively easily, i.e. to extract them from the object or array. A distinction is made between Array-Destructuring and Object-Destructuring.


1. Extract values from arrays

Array-Destructuring makes it easy to assign the values of an array to a series of variables. This can save you a lot of typing.


Extract values from arrays without destructuring

If you want to assign different variables to the values in an array, you have to assign each value from the array individually without destructuring:

Complete Code - Examples/Part_173/main.js...

 const mostUsedBrowser = [
   'Google Chrome',
   'Safari',
   'Firefox',
   'Edge'
 ];
 const one = mostUsedBrowser[0];
 const two = mostUsedBrowser[1];
 const three = mostUsedBrowser[2];
 const four = mostUsedBrowser[3];
                            

Extract values from arrays with destructuring

Destructuring makes it much easier and clearer. The values that you want to assign to the values from the corresponding array are written comma-separated , in square brackets [] after the variable keyword (let or const). The values are extracted from the array in the order in which they are to be extracted. This means that the first variable receives the value of index 0, the second variable the value of index 1 and so on.

Complete Code - Examples/Part_174/main.js...

 const mostUsedBrowser = [
   'Google Chrome',
   'Safari',
   'Firefox',
   'Edge'
 ];

 const [
   one,
   two,
   three,
   four,
   five
   ] = mostUsedBrowser;

 console.log(one);   // "Google Chrome"
 console.log(two);   // "Safari"
 console.log(three); // "Firefox"
 console.log(four);  // "Edge"
                            

The original values are of course retained, even if the term extract and extracted values is used here.


Use existing variables for destructuring

If the variables to which the values are to be assigned already exist and do not have to be declared first, let can also be omitted (const cannot be used here) and the destructuring statement can begin directly with the opening square bracket:

Complete Code - Examples/Part_175/main.js...

 ...
 let one;
 let two;
 let three;
 let four;

 [
   one,
   two,
   three,
   four
 ] = mostUsedBrowser;
                            

Value assignment with fewer elements in array

If the array contains fewer elements than the number of variables specified, the corresponding variable is assigned the value undefined:

Complete Code - Examples/Part_176/main.js...

 const mostUsedBrowser = [
   'Google Chrome',
   'Safari',
   'Firefox',
   'Edge'
 ];
 const [
   one,
   two,
   three,
   four,
   five
   ] = mostUsedBrowser;
 console.log(five); // undefined
                            

Define default values for variables

Alternatively, with array structuring, as with function parameters, you can specify default values for variables. Instead of undefined, the corresponding variable is then assigned the default value if no corresponding entry exists in the array.

Complete Code - Examples/Part_177/main.js...

 const mostUsedBrowser = [
   'Safari',
   'Firefox'
 ];
 const [
   one = 'Google Chrome',
   two = 'Google Chrome',
   three = 'Google Chrome',
   four = 'Google Chrome'
   ] = mostUsedBrowser;
 console.log(one); // "Safari";
 console.log(two); // "Firefox";
 console.log(three); // "Google Chrome";
 console.log(four); // "Google Chrome";
                            

Extract only certain values

If only certain values from the array are to be mapped, this is possible by not specifying a variable in the corresponding position:

Complete Code - Examples/Part_178/main.js...

 const mostUsedBrowser = [
   'Google Chrome',
   'Safari',
   'Firefox',
   'Edge'
 ];
 const [
   one,
   , // No variable is entered here
   three,
   four
   ] = mostUsedBrowser;
 console.log(one);     // "Google Chrome"
 // console.log(two);  // Error, as not defined
 console.log(three);   // "Firefox"
 console.log(four);    // "Edge"
                            

Here, no further variable was specified between the variables one and three, but the corresponding position was left empty. The value Google Chrome from the array is assigned to the variable one, the value Safari to no variable and the values Firefox and Edge to the variables three and four.


Extract values from multidimensional arrays

Create a multidimensional array:


 const coordinates = [
   [2,3,4],
   [5,6,7],
   [8,9,10]
 ];
                            

Array destructuring of a multidimensional array:


 const [
   [x1,y1,z1],
   [x2,y2,z2],
   [x3,y3,z3]
 ] = coordinates;
                            

2. Extract values from objects

The destructuring of objects works in the same way as array destructuring. The notation here is also opposite to the construction of objects.

Creating an object compared to object destructuring:

Complete Code - Examples/Part_179/main.js...

 // Construction of a "normal" object
 const person = {
   firstName : 'Rick',
   lastName : 'Sample'
 };

 // Object destructuring
 const {
   firstName : firstNameExtracted,
   lastName : lastNameExtracted
   } = person;
                        

If variables and object properties are the same, extraction is even easier:


 // Object destructuring with variables and object properties of the same name
 const person = {
   firstName : 'Rick',
   lastName : 'Sample'
 };

 const {
   firstName,
   lastName
   } = person;
                        

Here, the two variables firstName and lastName are exactly the same as the object properties of person. A corresponding assignment of property values to variables is then carried out implicitly.


Extract values from nested objects

Complete Code - Examples/Part_180/main.js...

 const person = {
   firstName : 'Rick',
   lastName : 'Sample',
   address : {
     postCode : '420',
     street : 'Milky Way 42'
   }
 }
 const {
   firstName : firstNameExtracted,
   lastName : lastNameExtracted,
   address : {
     postCode : postCodeExtracted,
     street : streetExtracted
     }
   } = person;
 console.log(firstNameExtracted);  // "Rick"
 console.log(lastNameExtracted);   // "Sample"
 console.log(postCodeExtracted);   // "420"
 console.log(streetExtracted);     // "Milky Way 42"
                            

Alternatively, another example if the object properties are to be extracted into variables with the same name:

Complete Code - Examples/Part_181/main.js...

 ...
 const {
   firstName,
   lastName,
   address : {
     postCode,
     street
     }
   } = person;
 console.log(firstName);   // "Rick"
 console.log(lastName);    // "Sample"
 console.log(postCode);    // "420"
 console.log(street);      // "Milky Way 42"
                            

Combine object destructuring with array destructuring

Object destructuring and array destructuring also work in combination:

Complete Code - Examples/Part_182/main.js...

 const person = {
   firstName : 'Rick',
   lastName : 'Sample',
   address : {
     postCode : '420',
     street : 'Milky Way 42'
   },
   phoneNumbers : [
     '0169/12345677',
     '0169/12345679'
   ]
 }
 const {
   firstName : firstNameExtracted,
   lastName : lastNameExtracted,
   address : {
     postCode : postCodeExtracted,
     street : streetExtracted
     },
   phoneNumbers : [
     phoneNumber1Extracted,
     phoneNumber2Extracted
     ]
   } = person;
 console.log(firstNameExtracted);      // "Rick"
 console.log(lastNameExtracted);       // "Sample"
 console.log(postCodeExtracted);       // "420"
 console.log(streetExtracted);         // "Milky Way 42"
 console.log(phoneNumber1Extracted);   // "0169/12345677"
 console.log(phoneNumber2Extracted);   // "0169/12345679"
                            

An object is shown here that contains an array of strings behind the phoneNumbers property, whereby these strings are extracted in the two variables phoneNumber1Extracted and phoneNumber2Extracted.

With more complex hierarchies in the code, the destructuring of arrays and objects should not be exaggerated too much so that the code does not become confusing.


3. Extract values within a loop

Destructurings can also be used within a for-of loop:

Complete Code - Examples/Part_183/main.js...

 const persons = [
     {
       firstName: 'Rick',
       lastName: 'Sample',
       contact: {
         email: 'rick.sample@mail.com',
         phone: '0169/12345677'
       }
     },
     {
       firstName: 'Morty',
       lastName: 'Sample',
       contact: {
         email: 'morty.sample@mail.com',
         phone: '0169/12345679'
       }
     }
   ];

   for (const { firstName, lastName, contact: { email, phone } } of persons) {
     console.log(`${firstName} ${lastName}`);
     console.log(`E-Mail: ${email}`);
     console.log(`Phone: ${phone}`);
   }

 /* output:
 Rick Sample
 E-Mail: rick.sample@mail.com 
 Phone: 0169/12345677
 Morty Sample
 E-Mail: morty.sample@mail.com
 Phone: 0169/12345679
 */
                        

Here, the array persons is defined first, which contains objects with information on persons and their contact details. A for-of loop is then used to iterate over the array. Destructuring within the loop means that a destructuring statement is applied to the current object in each iteration, i.e. the values from the object properties are extracted from the object.

A shorter version of the same example:

Complete Code - Examples/Part_184/main.js...

 const persons = [
     {
       firstName: 'Rick',
       lastName: 'Sample',
       contact: {
         email: 'rick.sample@mail.com',
         phone: '0169/12345677'
       }
     },
     {
       firstName: 'Morty',
       lastName: 'Sample',
       contact: {
         email: 'morty.sample@mail.com',
         phone: '0169/12345679'
       }
     }
   ];

   for (let {firstName:f, lastName:l, contact:{email:e, phone:p}} of persons) {
     console.log(`${f} ${l}`);
     console.log(`E-Mail: ${e}`);
     console.log(`Phone: ${p}`);
   }
                        

4. Extract arguments of a function

The next example shows the extraction of function arguments using destructuring:

Complete Code - Examples/Part_185/main.js...

 function printPerson(
   {
     firstName: firstName,
     lastName: lastName,
     contact: {
       email: email,
       phone: phone
       }
     }
 ) {
   console.log(`${firstName} ${lastName}`);
   console.log(`E-Mail: ${email}`);
   console.log(`Phone: ${phone}`);

 }
 const person = {
   firstName: 'Rick',
   lastName: 'Sample',
   contact: {
     email: 'rick.sample@mail.com',
     phone: '0169/12345679'
   }
 };
 printPerson(person);

 /* output:
 Rick Sample
 E-Mail: rick.sample@mail.com
 Phone: 0169/12345679 
 */
                        

The printPerson() method applies destructuring to an object; the object is passed to the method as an argument. The values are extracted from the passed object as variables or parameters and made available within the function.

The next example shows the extraction of part of the object properties using destructuring:

Complete Code - Examples/Part_186/main.js...

 function printContactInformation(
   {
     contact: {
       email: email,
       phone: phone
       }
     }
 ) {
   console.log(`E-Mail: ${email}`);
   console.log(`Phone: ${phone}`);
 }
 const person = {
   firstName: 'Rick',
   lastName: 'Sample',
   contact: {
     email: 'rick.sample@mail.com',
     phone: '0169/12345679'
   }
 };
 printContactInformation(person);

 /* output:
 E-Mail: rick.sample@mail.com
 Phone: 0169/12345679
 */
                        

Only the properties email and phone are extracted here, the other properties are not taken into account.


5. Copy object properties to another object

Rest parameters can be used to provide any number of function parameters as an array. With ES2018, so-called Rest-Properties were introduced, which enable something similar for object properties. Rest properties are defined using three preceding dots ....

The statement:


 const {
   firstName,
   lastName,
   ...properties
 } = person;
                        

This statement ensures that all properties of the person object that are defined as enumerable and are not assigned to another variable via the destructuring rule (firstName and lastName) are copied to the properties object:

Complete Code - Examples/Part_187/main.js...

 const person = {
   firstName: 'Rick',
   lastName: 'Sample',
   age: 62,
   hairColor: 'gray',
   height: 1.7
 };
 const {
   firstName,
   lastName,
   ...properties
 } = person;
 console.log(firstName);  
 console.log(lastName);  
 console.log(properties); 

 /* output:
 Rick
 Sample
 { age: 62, hairColor: 'gray', height: 1.7 }
 */
                        

More about rest parameters click here.


6. Copy object properties from another object

Spread properties behave in a similar way to the spread operator. Using this operator, it is possible to distribute values that are present in an array to several elements, e.g. function parameters. Spread properties work in a similar way for objects:

Complete Code - Examples/Part_188/main.js...

 const firstName = 'Rick';
 const lastName = 'Sample';
 const properties = {
   age: 62,
   hairColor: 'gray',
   height: 1.7
 };
 const person = {
   firstName,
   lastName,
   ...properties
 };
 console.log(person);

 /* output:
 {
 firstName: 'Rick',
 lastName: 'Sample',
 age: 62,
 hairColor: 'gray',
 height: 1.7
 }
 */
                        

Here, the statement copies all properties of the object properties (which are enumerable) to the object person.


Related links: