freeCodeCamp/curriculum/challenges/english/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-nested-objects.english.md
Randell Dawson 05f73ca409 fix(curriculum): Convert blockquote elements to triple backtick syntax for JavaScript Algorithms and Data Structures (#35992)
* fix: convert js algorithms and data structures

* fix: revert some blocks back to blockquote

* fix: reverted comparison code block to blockquotes

* fix: change js to json

Co-Authored-By: Oliver Eyton-Williams <ojeytonwilliams@gmail.com>

* fix: convert various section to triple backticks

* fix: Make the formatting consistent for comparisons
2019-05-17 08:20:30 -05:00

2.0 KiB

id, title, challengeType
id title challengeType
587d7b89367417b2b2512b4a Use Destructuring Assignment to Assign Variables from Nested Objects 1

Description

We can similarly destructure nested objects into variables. Consider the following code:
const a = {
  start: { x: 5, y: 6 },
  end: { x: 6, y: -9 }
};
const { start: { x: startX, y: startY }} = a;
console.log(startX, startY); // 5, 6

In the example above, the variable startX is assigned the value of a.start.x.

Instructions

Use destructuring assignment to obtain max of forecast.tomorrow and assign it to maxOfTomorrow.

Tests

tests:
  - text: <code>maxOfTomorrow</code> equals <code>84.6</code>
    testString: assert(getMaxOfTmrw(LOCAL_FORECAST) === 84.6, '<code>maxOfTomorrow</code> equals <code>84.6</code>');
  - text: nested destructuring was used
    testString: getUserInput => assert(getUserInput('index').match(/\{\s*tomorrow\s*:\s*\{\s*max\s*:\s*maxOfTomorrow\s*\}\s*\}\s*=\s*forecast/g),'nested destructuring was used');

Challenge Seed

const LOCAL_FORECAST = {
  today: { min: 72, max: 83 },
  tomorrow: { min: 73.3, max: 84.6 }
};

function getMaxOfTmrw(forecast) {
  "use strict";
  // change code below this line
  const maxOfTomorrow = undefined; // change this line
  // change code above this line
  return maxOfTomorrow;
}

console.log(getMaxOfTmrw(LOCAL_FORECAST)); // should be 84.6

Solution

const LOCAL_FORECAST = {
  today: { min: 72, max: 83 },
  tomorrow: { min: 73.3, max: 84.6 }
};

function getMaxOfTmrw(forecast) {
  "use strict";
  // change code below this line
   const {tomorrow : {max : maxOfTomorrow}} = forecast; // change this line
  // change code above this line
  return maxOfTomorrow;
}

console.log(getMaxOfTmrw(LOCAL_FORECAST)); // should be 84.6