Welcome back to DailyJS, as you know these days we are discussing various use cases of the concept of destructuring in JavaScript.
On the previous day we discussed how can we pull out a property inside an object which is inside an array.
Today we will look at the opposite, how to extract out an array element which is inside an object property.
To see this, we will look at a simple example
Given the details of a student in an object, extract out his marks in physics, chemistry and maths
Let's solve this problem without destructuring first!
var student = {
name: 'John',
age: 17,
marks: [95, 91, 89] // [ P, C, M ]
};
var phy = student.marks[0];
var chem = student.marks[1];
var mat = student.marks[2];
console.log (`P: ${phy} | C: ${chem} | M: ${mat}`);
Again, we are writing student.marks
3 times, let's have a look at the solution through destructuring
var student = {
name: 'John',
age: 17,
marks: [95, 91, 89] // [ P, C, M ]
};
const { marks: [physics, chemistry, maths] } = student;
console.log (`P: ${physics} | C: ${chemistry} | M: ${maths}`);
As you can see, we reduced the 3 lines of extraction to a single line.
That's it for today, see you tomorrow.