Use Destructuring Assignment to Assign Variables from Objects
Destructuring allows you to assign a new variable name when extracting values. You can do this by putting the new name after a colon when assigning the value.
Using the same object from the last example:
const user = { name: 'John Doe', age: 34 };
Here's how you can give new variable names in the assignment:
const { name: userName, age: userAge } = user;
You may read it as "get the value of user.name and assign it to a new variable named userName" and so on. The value of userName would be the string John Doe, and the value of userAge would be the number 34.
Use Destructuring Assignment to Assign Variables from Nested Objects
You can use the same principles from the previous two lessons to destructure values from nested objects.
Using an object similar to previous examples:
const user = {
johnDoe: {
age: 34,
email: 'johnDoe@freeCodeCamp.com'
}
};
Here's how to extract the values of object properties and assign them to variables with the same name:
const { johnDoe: { age, email }} = user;
And here's how you can assign an object properties' values to variables with different names:
const { johnDoe: { age: userAge, email: userEmail }} = user;
More examples to understand the destructuring:
Example 1:
const obj1 = {name: "mozahedul",title: "student",address: {city: "Dhaka",District: "Rangpur",},};const {name: firstName, // this is used for rename of object element;title,favoritePlace = "medina",} = obj1;console.log(firstName);// Result: mozahedulconsole.log(title);// Result: studentconsole.log(favoritePlace);// Result: medina
Example 2:
const obj1 = {name: "mozahedul",title: "student",favoritePlace: "Mecca",address: {city: "Dhaka",District: "Rangpur",},};const {name: firstName, // this is used for rename of the element of an object;title,...rest} = obj1;console.log(firstName);// Result:// mozahedulconsole.log(rest);/*favoritePlace: "Mecca",address: {city: "Dhaka",District: "Rangpur",}*/
Post a Comment