Javascript- Object Destructuring

Object Destructuring was introduced in ES6 version of Javascript

Destructuring simplifies extracting values from arrays and objects.

Before ES6

In order to access the properties of objects, we had to call them like this:

var person = {
	name: 'sujay kundu',
	age: 23,
	role: 'software engineer'
}

var name = person.name;
var age = person.age;
var role = person.role;

console.log(name, age, role);
JavaScript

With ES6

Now we can use object destructuring, we have simple syntax to access the properties of objects

Object destructuring uses object literals syntax {}

var person = {
 name: 'sujay kundu',
 age: 23,
 role: 'software engineer'
}

let {name, age} = person;
console.log(name, age); //sujay kundu 23

let {name, age, role} = person
console.log(name, age, role); // sujay kundu 23 software engineer

let {name, role} = person;
console.log(name, role); // sujay kundu software engineer
JavaScript

We can now access any properties from the object and assign it to the variable name and the property name is same so we are just destructuring it.

let {role} = person;

Removes the person.role and assign it the variable named role.

If we want to use a different variable name then we can do it like below:

let {name: fullName, age: completeAge, role: designation} = person;

console.log(fullName, completeAge, designation);
// sujay kundu 23 software engineer
JavaScript

let {name: fullName} pulls the person.name property and assign it to the fullName variable.

Defauly values can also be assigned to the variables.

let person = {
	name: 'sujay kundu',
	age: 23,
}

let {name: fullName, age: completeAge, role:designation = 'Engineer');

console.log(fullName, age, designation);
// sujay kundu 23 Engineer
JavaScript

Nested objects destructuring

We can also use the destructuring for nested objects.

let person = {
	name: 'sujay kundu',
	age: 23,
	address: {
		street: 'random',
		city: 'bangalore',
		pincode: 560060
	}
}

let { address: {street, city}} = person;
console.log(street, city); // random bangalore
JavaScript

Custom variables with nested objects destructuring.

let {address: {street: completeStreet, city: completeCity}} = person;

console.log(completeStreet, completeCity);
// random bangalore
JavaScript

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *