In JavaScript, you can destructure an object by extracting one or more properties from the object and assigning them to variables. You can also rename the variables during the destructuring process. Here is an example of how to destructure and rename objects in JavaScript:
const person = {
name: "John",
age: 30,
occupation: "Software Engineer",
country: "USA",
};
// Destructure the person object and rename the properties
const { name: fullName, age, occupation: jobTitle, country: nation } = person;
console.log(fullName); // "John"
console.log(age); // 30
console.log(jobTitle); // "Software Engineer"
console.log(nation); // "USA"
In the above example, we are destructuring the person
object and assigning the name
property to a new variable named fullName
. We are also renaming the occupation
property to jobTitle
and the country
property to nation
.
Note that the variable names before the :
character are the new variable names you want to use, while the variable names after the :
character are the original property names of the object.
You can also destructure nested objects and rename their properties using the same syntax. For example:
const user = {
name: "Jane",
age: 25,
address: {
city: "New York",
state: "NY",
},
};
// Destructure the user object and rename the nested properties
const { name, age, address: { city: cityName, state: stateCode } } = user;
console.log(name); // "Jane"
console.log(age); // 25
console.log(cityName); // "New York"
console.log(stateCode); // "NY"
In the above example, we are destructuring the address
object nested inside the user
object and assigning the city
property to a new variable named cityName
. We are also renaming the state
property to stateCode
.
+ There are no comments
Add yours