Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution.
In later challenges you will appreciate the ability to destructure ojbects in this manner. It definitely streamlines the code as pointed out by @snowmonkey. Another advantage comes when you start destructuring a functions parameters. This is covered near the end of the ES6 section, but I will explain the benefit here, so that when you see it later, you will hopefully make the connection.
Let’s say I have manually created a large nested object like the following which represents classes a student might take in school.
let myClasses = {
English: {
credits: 3,
meets: 'Monday, Wednesday',
professor: 'Dr. Poet',
gradedWork: {
homework: {
percent: 0.2,
grades: [
{
date: '08-16-2018',
grade: 96
},
{
date: '09-01-2018',
grade: 90
}
]
},
quizzes: {
percent: 0.4,
grades: [
{
date: '08-17-2018',
grade: 87
},
{
date: '09-03-2018',
grade: 91
}
]
},
tests: {
percent: 0.4,
grades: [
{
date: '10-15-2018',
grade: 89
},
{
date: '11-01-2018',
grade: 95
}
]
}
}
},
Physics: {
credits: 5,
meets: 'Monday, Wednesday, Friday',
professor: 'Dr. Einstein',
gradedWork: {
homework: {
percent: 0.1,
grades: [
{
date: '08-4-2018',
grade: 90
},
{
date: '09-02-2018',
grade: 91
}
]
},
quizzes: {
percent: 0.6,
grades: [
{
date: '08-12-2018',
grade: 87
},
{
date: '09-20-2018',
grade: 98
}
]
},
tests: {
percent: 0.3,
grades: [
{
date: '10-11-2018',
grade: 92
},
{
date: '11-10-2018',
grade: 90
}
]
}
}
}
};
Now let’s say I have a function called calcGrade, which accepts an object (a subject property of myClasses) and calculates the student’s grade for just the subject object. I could write the following functions and use destructuring in various places to make the calculations easier to read:
/* uses parameter object destructuring in the reduce callback function
parameters to isolate the grade property */
const avgGrade = grades => grades.reduce((sum, { grade }) => sum + grade, 0) / grades.length;
/* uses object destructuring in the functions parameters, to create
readable variable names used in the calculation which is returned */
const calcGrade = ({
gradedWork: {
homework: { percent: hmPerc, grades: hm },
quizzes: { percent: qzPerc, grades: qz },
tests: { percent: testPerc, grades: test }
}
}) => hmPerc * avgGrade(hm) + qzPerc * avgGrade(qz) + testPerc * avgGrade(test)
const { Physics: grades } = myClasses; // basic object destructuring to get the applicable subject object
console.log('My Physics grade is ' + calcGrade(grades)); // displays 'My Physics grade is 91.85'