
JavaScript Object Destructuring
JavaScript object destructuring assigns properties of an object to individual variables.
Introduction to the JavaScript object destructuring assignment
Suppose you have a person object with two properties: firstName and lastName.
let person = {
firstName: 'Priyanka',
lastName: 'Reddy'
};
when you want to assign properties of the person object to variables, you typically do it like this:
let firstName = person.firstName; let lastName = person.lastName;
ES6 introduces the object destructuring syntax that provides an alternative way to assign properties of an object to variables:
let { firstName: fname, lastName: lname } = person;
In this example, the firstName and lastName properties are assigned to the fName and lName variables respectively.
In this syntax:
let {property1:variable1, property2:variable2}=object
The identifier before the colon (:
) is the property of the object and the identifier after the colon is the variable. If the variables have the same names as the properties of the object, you can make the code more concise as follows:
let {firstName, lastName} = person;
console.log(firstName); // Priyanka
console.log(lastName); // Reddy
In this example, we declared two variables firstName and lastName, and assigned the properties of the person object to the variables in the same statement.