{"id":11744,"date":"2022-07-21T15:49:17","date_gmt":"2022-07-21T15:49:17","guid":{"rendered":"https:\/\/www.htmlgoodies.com\/?p=11744"},"modified":"2022-07-21T15:49:17","modified_gmt":"2022-07-21T15:49:17","slug":"destructuring-javascript-objects","status":"publish","type":"post","link":"https:\/\/www.htmlgoodies.com\/javascript\/destructuring-javascript-objects\/","title":{"rendered":"Destructuring Mixed Objects and Function Arguments in ES6"},"content":{"rendered":"
<\/p>\n
Object destructuring is a useful JavaScript (ECMAScript 6) feature to extract properties from objects and bind them to variables. As we saw in the ES6 Object Destructuring<\/a> tutorial, object destructuring can extract multiple properties in one statement, access properties from nested objects, and can set a default value if the property does not exist. In today’s follow-up, we will be taking a look at mixed (Object and Array) destructuring, as well as how to destructure function and method arguments.<\/p>\n As alluded to in the intro, mixed destructuring involves the declaring and setting of variables from an object that contains attributes of Arrays or from an Array of Objects. To illustrate, here’s a <b>Person Object<\/b> that contains nested elements of both Objects and Arrays:<\/p>\n We can then employ ES6 Destructuring to assign all object properties to individual variables by replicating the object structure:<\/p>\n We can also use ES6 Destructuring to assign Array elements to individual variables, as long as we know the array’s length before-hand. Here is an example that shows how it is done:<\/p>\n The trick is to replace the element values with variables in which to store them.<\/p>\n Read<\/strong>: A guide to Working with CSS Variables<\/a><\/p>\n Objects passed to functions can be destructured within the function signature where function arguments are defined. This time, we would replicate the object structure in the arguments list:<\/p>\n Like any function parameters, we can assign default values to our local variables right in the function signature. Here is the displayEmployeeInfo()<\/strong> function again with default values assigned to the skills, languages and database variables:<\/p>\n Note that, even though we have specified default values for some of the variables, if we were to call the displayEmployeeInfo()<\/strong> function with no arguments we would get an error because destructured parameters are always required.<\/p>\n The key to avoiding the above error is to assign a fallback object literal for all higher-level objects, including the programmer object and the nested skills object.<\/p>\n In this web development tutorial, we explored a couple of the more advanced applications of ES6 destructuring syntax. As powerful as destructuring is on its own, they are capable of streamlining your code even further when combined with other ES6 features such Spread Syntax and Rest Parameters.<\/p>\n You will find a demo<\/a> of today’s code examples on codepen.io<\/a>. There, you can look over the code and observer the output produced.<\/p>\nWhat is Mixed Destructuring in JavaScript?<\/h2>\n
const person = {\r\n name: 'Rob',\r\n location: {\r\n city: 'Ottawa',\r\n country: 'Canada',\r\n phoneNumbers: ['555-1234', '555-2345'],\r\n },\r\n};\r\n<\/pre>\n
const {\r\n name,\r\n location: {\r\n city,\r\n country,\r\n phoneNums: [phone1, phone2],\r\n },\r\n} = person;\r\n\r\n\/\/ Now we can reference each variable without having to use dot (.) attribute accessors.\r\n\/\/ Outputs \"I am Rob from Ottawa, Canada. You can reach me at 555-1234 or 555-2345.\"\r\nconsole.log(\r\n `I am ${name} from ${city}, ${country}. You can reach me at ${phone1} or ${phone2}.`\r\n);\r\n<\/pre>\n
const dataArray = [\r\n { data: 1 },\r\n { data: 2 },\r\n { data: 3 }\r\n];\r\n\r\nconst [\r\n { data: val0 },\r\n { data: val1 },\r\n { data: val2 }\r\n] = dataArray;\r\n\r\n\/\/Outputs \"1, 2, 3\"\r\nconsole.log(`${val0}, ${val1}, ${val2}`);\r\n<\/pre>\n
Destructuring Object Function Arguments in JavaScript<\/h2>\n
\/\/Programmer Object containing nested elements\r\nconst programmer = {\r\n name: 'George',\r\n age: 29,\r\n skills: {\r\n languages: 'JavaScript, HTML, CSS',\r\n databases: 'MySQL, MS SQL, MongoDB',\r\n },\r\n};\r\n\r\n\/\/The programmer object is destructured within the parameters of the function that is passed in\r\nconst displayEmployeeInfo = ({ name, age, skills: { languages, databases } }) => {\r\n console.log(\r\n `The employee name is ${name} and his age is ${age}. \r\n\t\t He knows the following languages - ${languages} \r\n\t\t and is familiar with the databases - ${databases}.`\r\n );\r\n}\r\n\r\n\/\/Invoke the displayEmployeeInfo() function with the programmer object\r\n\/\/Output: The employee name is George and his age is 29. He knows the following \r\n\/\/languages - JavaScript, HTML, CSS and is familiar with the databases - MySQL, \r\n\/\/MS SQL, MongoDB \r\ndisplayEmployeeInfo(
Destructured Parameters and Default Values<\/h3>\n
\/\/Programmer Object without skills\r\nconst programmer = {\r\n name: 'George',\r\n age: 29,\r\n skills: {\r\n languages: 'JavaScript, HTML, CSS'\r\n }\r\n};\r\n\r\nconst displayEmployeeInfo = ({ name, age, skills: { languages = 'none', databases = 'none' } }) => {\r\n console.log(\r\n `The employee name is ${name} and his age is ${age}. \r\n He knows the following languages - ${languages} \r\n and is familiar with the databases - ${databases}.`\r\n );\r\n}\r\n\r\n\/\/Invoke the displayEmployeeInfo() function with the programmer object\r\n\/\/Output: The employee name is George and his age is 29. He knows the following \r\n\/\/languages - JavaScript, HTML, CSS and is familiar with the databases - none\r\ndisplayEmployeeInfo(
Making Destructured Parameters Optional<\/h3>\n
const displayEmployeeInfo = ({ name, age, skills: { languages = 'none', databases = 'none' } }) => {\r\n console.log(\r\n `The employee name is ${name} and his age is ${age}. \r\n He knows the following languages - ${languages} \r\n and is familiar with the databases - ${databases}.`\r\n );\r\n}\r\n\r\n\/\/Invoking the displayEmployeeInfo() function with no arguments\r\n\/\/throws the Error \"TypeError: (destructured parameter) is undefined\"\r\ndisplayEmployeeInfo(); \r\n<\/pre>\n
const displayEmployeeInfo = ({ name = \"John Doe\", age = \"unknown\", skills: { languages = 'none', databases = 'none' } = {} } = {}) => {\r\n document.write(\r\n `The employee name is ${name} and his age is ${age}. \r\n He knows the following languages - ${languages} \r\n and is familiar with the databases - ${databases}.`\r\n );\r\n}\r\n\r\n\/\/Invoking the function displayEmployeeInfo with the programmer object\r\n\/\/Output: The employee name is John Doe and his age is unknown. He knows the following \r\n\/\/languages - none and is familiar with the databases - none\r\ndisplayEmployeeInfo(); \r\n<\/pre>\n
Final Thoughts on Destructuring Mixed Objects and Function Arguments in ES6<\/h2>\n