This content originally appeared on DEV Community and was authored by Atif Aiman
Salam, and well, hello everyone!
Have you ever thought about the data structure of an array or object, with the most complex structure, and try to call a parameter that lives deep inside the dungeon of the object? Well, students[4].subjects[2].information.lecturers[1]
indeed seems horrifying, especially when you had to repeat the code throughout your codebases đź’€
There's a solution for that! But to understand how it works, we need to go for the conventional way first to see how it evolves into "destructuring". So, what is "destructure" in Javascript?
Destructuring
Well, time for imagination. A box. Full of items. Later, you have to remember each of them just to play with them. Instead of remembering where it locates inside the box, you unpack the box and name it accordingly, so it will be easier to play with them later on. And it is not necessary to unpack everything, you can just unpack whatever you need.
In Javascript, you can "unpack" whatever you need inside an object and arrays. Yes, both of them! But, how does it look like?
There are three parts of destructuring that you need to pay attention to. First is, of course, the original object or array. It's impossible to destructure something that doesn't exist.
And here we come...
const team = {
name: "Team Secret",
region: "Europe",
members: ["MATUMBAMAN", "Nisha", "zai", "YapzOr", "Puppey"],
year: 2021,
coach: "Heen",
captain: "Puppey",
isFinalist: true,
};
Let us consider the object above is the one we want to play with. Object with 6 entries, with each of them, has different value types. Cool. So, how do we want to call the region, as an example?
console.log(team.region);
// Europe
As easy as TI, right? Huh, I mean, ABC! Cool. Now, how about calling Nisha?
console.log(team.members[1]);
// Nisha
Still easy. So, just imagine you have to call the same exact thing at multiple places, so how will it be?
...and we come from a long way...
From this point, instead, I want to call it the long way, I just want to call what is necessary. Not every entry in the team
object will be used. So, getting the members...
const members = team.members;
console.log(members[2]);
// zai
And now, I need members, captain, and name of the team.
const teamName = team.name;
const captain = team.captain;
const members = team.members;
So, just imagine, if we deal with a big object, that means that the code above will be bigger as well if the need increases as well. But, just to give an idea, we rename the object values to the new variable declaration. Easier to read, but a bit redundant work here.
I need you to put attention to two things here. We call the original index (or key), and then rename it by declaring a new variable, so we don't need to call the object anymore, since the new variable is declared using the object values.
const teamName = team.name;
const captain = team.captain;
const members = team.members;
------- -------------
rename original index
...to be better every day
Let's dive slowly to destructuring. The same idea that we discussed before, I will demonstrate how we use destructuring for better syntax.
const { members: teamMembers } = team;
--------- --------------
original index rename
console.log(teamMembers[0]);
// MATUMBAMAN
With this, you don't need to use the standard declaration way and start using destructuring way. And, you can still access the object the normal way as well, since it doesn't change the original object. It just creates a new variable during destructuring.
const { members: teamMembers } = team;
console.log(teamMembers[0]);
// MATUMBAMAN
console.log(team.captain);
// Puppey
Without renaming
There is a time, you feel that renaming is unnecessary, and that happens! If that is the case, you can just omit the renaming, and just use the original index (or key).
const { members } = team;
console.log(members[4]);
// Puppey
As you can see, destructuring can be as simple as that! Just use the original key name, and you are good to go. So, let's destructure everything!
const {
name,
region,
members,
year,
coach,
captain,
isFinalist,
} = team;
And yes, as simple as that!
Destructure one and retain others
For this case, let's assume this is the case.
const members = team.members;
const otherInfo = {
name: team.name,
region: team.region,
year: team.year,
coach: team.coach,
captain: team.captain,
isFinalist: team.isFinalist,
};
What have you noticed here? Well, we can see we declare members, which can later be simplified with the destructuring method. But how about the next one, which is otherInfo
? It has everything the team has, except for members! So it has the rest of them after declaring members.
For this case, we will learn to use a spread operator, where it will take everything else, and put it inside a new name for it.
const {
members,
...otherInfo
} = team;
console.log(otherInfo.coach);
// Heen
Shorter, simpler, and easier to read, right? Since "the rest" didn't have any key it refers to, the way it writes is just ...rest
. After spread operator (...
), put any name you want.
You can also do a mix of everything!
const {
members,
captain: teamCaptain,
year: competeYear,
...theRest
} = team;
Everything has its beginning
There is a time, where the object key didn't exist, so you want to initialize it first. So, can we do that? Of course!
const {
director,
} = team;
// This will return error, since director
// is not in `team` object
const {
director = "John Yao",
} = team;
// This will not produce error, because
// the `director` will be initialized since
// director is not exist. Yet.
Can we also use this to the existing key? The answer is yes!
const {
coach = "Atif",
} = team;
// This will not produce error. However, you
// will get "Heen" later on, since coach is already
// has value in the object.
Using this way, it will initialize it to "Atif", only when the coach isn’t existed or undefined.
Put everything in one place
const {
members,
captain: teamCaptain = "Aiman",
year: competeYear,
manager = "Cyborgmatt",
...theRest
} = team;
console.log(members[3]); // YapzOr
console.log(teamCaptain); // Pupper
// Team captain already initialized in the original object
console.log(competeYear); // 2021
console.log(manager); // Cyborgmatt
console.log(theRest.coach); // Heen
And, how about the object inside the object?
const team = {
name: "Team Secret",
region: "Europe",
members: ["MATUMBAMAN", "Nisha", "zai", "YapzOr", "Puppey"],
year: 2021,
coach: "Heen",
captain: "Puppey",
isFinalist: true,
position: {
core: ["MATUMBAMAN", "zai"],
support: ["Puppey", "YapzOr"],
mid: ["Nisha"],
},
};
const {
position: {
core,
support,
mid,
},
} = team;
That's it! Just navigate through the nested object as usual. You can see the position
parameter I added, and later I destructure by using position
first and then destructure what is inside.
That is how you rock the object destructuring! But, how about arrays?
Destructuring in arrays
Do you notice that I keep on saying index/keys? Yup, the object has flexible indexing or what we call keys, so it's easy to destructure an object without any need to see the arrangement. But the issue is different with arrays since the index is in sequence.
const teamMembers = ["MATUMBAMAN", "Nisha", "zai", "YapzOr", "Puppey"];
We will start from here.
Destructure in sequence
Since the array's index is in sequence, we need to follow the arrangement when destructuring. With that, -
const [core1, mid, core2, support1, support2] = teamMembers;
console.log(core1); // MATUMBAMAN
So, you can see we destructure everything in the array. So, what if I only need the first 2? Well, just omit the rest!
const [core1, mid] = teamMembers;
console.log(mid); // Nisha
Then, how about the last 2? Because we need to put it in sequence, right? Well, you can leave it blank of course!
const [ , , , support1, support2] = teamMembers;
console.log(support2); // Puppey
Next! How about using a spread operator for the rest? Chill, we got this covered!
const [core1, mid, ...otherMembers] = teamMembers;
console.log(otherMembers);
// ["zai", "YapzOr", "Puppey"]
The spread operators will take the rest, and pass it as a new array. The spread operator first and then destructure the last 2? Stop right there! I am afraid that that is not possible unless you need to use .split
for that purpose.
What? Do you say you want to use the object way? Well, sure you can, but rename is compulsory then.
const {
0: core1,
1: mid,
} = teamMembers;
console.log(mid); // Nisha
So, that means, we can do things like destructure the middle and spread operator for the rest? Well well well, that works like jolly!
const {
2: core2,
...otherMembers
} = teamMembers;
console.log(core2); // zai
console.log(otherMembers);
// { 0: "MATUMBAMAN", 1: "Nisha", 3: "YapzOr", 4: "Puppey" }
// Note that `...otherMembers` will try to retain
// the index if destructure didn't happen at index 0,
// and will produce object instead.
Conclusion
That is everything about destructuring! From objects to arrays, we learn how to extract entries inside objects and arrays, so it will be easier for us to call later on. Note that destructuring will create a new variable in place without changing the original object or array. This is cooler when is used with functions.
const displayName = ({ player, coach, director = "Luck" }) => {
console.log(`Player is ${player}`);
console.log(`Director is ${director}`);
};
displayName({ coach: "Master", player: "Atif", director: "Life" });
// Player is Atif
// Director is Life
displayName({ coach: "Master", player: "Aiman" });
// Player is Aiman
// Director is Luck
// Note that I put coach first instead of player. And it still works!
In this way, you don't have to put the parameter in sequence anymore. Neat right?! And even, you can do default value, if the parameter is not passed!
So, thanks for the read, and until then, sayonara and peace be upon ya!
This content originally appeared on DEV Community and was authored by Atif Aiman
Atif Aiman | Sciencx (2021-10-16T18:02:53+00:00) Javascript – Destructuring the Thing!. Retrieved from https://www.scien.cx/2021/10/16/javascript-destructuring-the-thing/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.