I have this object
const storeObj = {
name: {
firstName: 'abc'
}
}
I can do alias by assigning name
to username
const { name: username } = storeObj
I can do nested destructuring like so
const { name: { firstName } } = storeObj
Can I use them both together? I want to achieve one line when aliasing aka renanming and nested destructuring.
Destructuring nested objectsIf we need to access an employee's info we can destructure as many levels as it takes to get to our employee object's properties. const { engineers: { 1: { id, name, occupation, }, }, } = employees; Now we have access to all of the second employee object's properties.
The destructuring is also possible for JavaScript Arrays. By default, the object key name becomes the variable that holds the respective value. So no extra code is required to create another variable for value assignment.
To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element. const [var1, var2, ...]
Yes, just put those two together - when you want to assign to a different variable name than the property name, put the new variable name after a colon. This works regardless of the level of the nested object.
const storeObj = {
name: {
firstName: 'abc'
}
}
const { name: { firstName: username } } = storeObj;
console.log(username);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With