Object Destructuring JavaScript
In this tutorial, we are going to learn about object destructuring in javascript.
So, let's get started...
What is Destructuring?
Destructuring is an ES6 feature and it's basically a way of unpacking values from an array or object into separate variables.
In other words, Destructuring is a way to break a complex data structure down into a smaller data structure like a variable.
In Object Destructuring Order of an element does not matter like an array, so provided the exact name of the property.
const sampleObj = {
name: 'Adam',
address: 'New york, 21',
age:'22'
};
const {age, name} = sampleObj ;
console.log(age, name);
//Output : 22, Adam
Note : When we destructure an array we use square brackets, when we destructure an object we use curly braces.
Using different property name
const {name:userName,age:ageNow} = sampleObj;
console.log(userName,ageNow);
//Output : Adam, 22
Setting Default values
const {languges=[],certificates = []} = sampleObj;
console.log(languges,certificates);
//Output : [],[]
Mutating variables
let m = 111;
let w = 999;
const obj = {m:23,w:7,c:14};
({m,w} = obj);
console.log(m,w);
//output : 23 7
Nested Objects
const users = {
name: 'Joy',
address: {
city: 'san francisco'
}
};
// Object destructuring:
const { address: { city } } = users;
city; // => 'san francisco'
Rest object after destructuring
const users = {
fname: 'Joy',
fullName: 'Joy Benrji',
job:'developer'
};
const { name, ...fullData } = users;
fullData ; // => { fullName: 'Joy Benrji' }
In above example, the destructuring const { name, ...fullData } = users
extracts the property fname and the remaining properties (fullName,job)
are collected into the variable fullData.