Object destructuring
The destructuring assignment also works with objects. The basic syntax is:
1let {var1, var2} = {var1:…, var2:…}
We have an existing object at the right side, that we want to split into variables. The left side contains a “pattern” for corresponding properties. In the simple case, that’s a list of variable names in `...`
For instance:
1let options = {
2 title: "Menu",
3 width: 100,
4 height: 200
5 };
6 let {title,width,height}=options;
For potentially missing properties we can set default values using "=" , like this:
1let options = {
2 title: "Menu",
3 width: 100,
4 height: 200
5 };
6 let{title2=100,width2}=options
7 console.log("title2",title2)
The rest pattern “…”
What if the object has more properties than we have variables? Can we take some and then assign the “rest” somewhere? We can use the rest pattern, just like we did with arrays. It’s not supported by some older browsers (IE, use Babel to polyfill it), but works in modern ones. It looks like this:
1let options = {
2 title: "Menu",
3 width: 100,
4 height: 200
5 };
6 let {title1,...rest}=options
7 console.log("title1",title1)
If we have a complex object with many properties, we can extract only what we need:
1let options = {
2 title: "Menu",
3 width: 100,
4 height: 200
5 };
6 // only extract title as a variable
7 let { title } = options;
8 alert(title); // Menu
Nested destructuring
If an object or an array contain other nested objects and arrays, we can use more complex leftside patterns to extract deeper portions. In the code below options has another object in the property size and an array in the property items . The pattern at the left side of the assignment has the same structure to extract values from them:
1let options = {
2 size: {
3 width: 100,
4 height: 200
5 },
6 items: ["Cake", "Donut"],
7 extra: true
8 };
9 let {
10 size: { // put size here
11 width,
12 height
13 },
14 items: [item1, item2], // assign items here
15 title = "Menu" // not present in the object (default value is used)
16 } = options;
17 console.log("CHciken",title)
Destructuring function arguments
Pull properties from an object passed into a function. This pattern simulates named parameters instead of relying on argument position.
1let user={
2 name:'Moiz',
3 subject:'Javascript',
4 id:1,
5 }
6 function test({name,subject})
7 {
8 console.log(hi my name is ${name} and I am learning ${subject})
9
10 }
11 test(user)
This also works for arrays:
1let part=['moix','king']
2 function testArray([first,second])
3 {console.log(hi name first name is ${first} and second name is ${second})}
4 testArray(part)
Nested Array Destructuring
1var arr=[1,2,[3,4],5]
2 var [a, , [b, c], d] = arr;
3console.log(a,c,d);
Renaming Variables While Destructuring
Destructuring allows us to refer to one key in an object, but declare it as a variable with a different name. The syntax looks like the key-value syntax for a normal JavaScript object.
1let user = {
2 name: 'John Smith',
3 id: 10,
4 email: 'johns@workcorp.com',
5 };
6 let {user: userName, id: userId} = user;
7 console.log(userName) // John Smith
8 console.log(userId) // 10
Default Value While Destructuring
We often encounter a situation where a property we're trying to extract doesn't exist in the object/array, resulting in a TypeError (while destructuring nested objects) or being set to undefined. While destructuring we can set a default value, which it will fallback to, in case of it not being found in the object.
1
2 var obj = {a : 1};
3var {a : x , b : x1 = 10} = obj;
4console.log(x, x1); // 1, 10
5var arr = [];
6var [a = 5, b = 10, c] = arr;
7console.log(a, b, c); // 5, 10, undefined
8
About
Moiz is a software engineer from Arid University with a passion for writing tech tutorials and doing coding. I am continously produce JavaScript and other web development technology tutorials in concepts through easy-to-understand explanations written in plain English.I have expertise in next js ,react js ,javascript,html,bootstrap and node js.
Follow him on TwitterHassan is a software engineer from kohat university of science and technology with a passion for writing tech tutorials and doing javascript practices on daily basis.I have expertise in next js ,react js ,javascript,html,bootstrap and node js. Problem Solving and making concpets is my strong point.
Follow him on TwitterTags
Click to see all tutorials tagged with: