A better way to split objects into variables
What is Destructuring?
Simply put, Destructuring is the new & better way of storing JavaScript Object values into individual variables.
Let's see how it works!
Consider you have an object called person
. And you want to store the individual values of the object person into separate variables.
const person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};
Traditionally, you will do something like this:
const firstName = person.firstName;
const lastName = person.lastName;
const age = person.age;
const eyeColor = person.eyeColor;
You will create variables of each name
from the object person
and assign it the value
of the same name
.
This method works!
But, lucky you, there is an even easier method through which you can get the job done with just one line of code instead of writing 4 lines of code.
As you guessed, it's called Destructuring. And this is how it works:
const { firstName, lastName, age, eyeColor } = person;
All you have to do is just put the names of the object within the {}
& assign it to the object person
.
That was easy right!
Merge variables into an object
Object Properties
Above, we saw how to split an object into individual variables. Now, what if you wish to do the reverse of it? How about merging multiple variables into an object? Let's talk about it!
Let's see how it works!
Suppose we want to merge variables a
, b
& c
, into an object called okObj
.
const a = 'test';
const b = true;
const c = 789;
Traditional this is how people do it:
const okObj = {
a: a,
b: b,
c: c
};
Again, this way works!
But there is an easy, one-liner way to achieve the same! Here it is:
const okObj = {a, b, c};
Cool, right! It will create an object with key names as the variables names and key values as object variables.
Final Takeaway!
Start using Destructuring & Object Properties in case you ever need to split up objects or merge variables into an object.
But feel free to stick to any other method you are comfortable with.
These are the new and best practices of writing modern javascript. Best of all it will save you precious seconds.
Support
Thank you so much for reading! I hope you found this blog post useful.
If you like my work please consider Buying me a Coffee so that I can bring more projects, more articles for you.
Also if you have any questions or doubts feel free to contact me on Twitter, LinkedIn & GitHub. Or you can also post a comment/discussion & I will try my best to help you :D
Top comments (1)
Create an object with properties removed.