Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using nested destructuring with aliasing for javascript Object [duplicate]

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.

like image 399
Melissa93 Avatar asked Jul 26 '18 03:07

Melissa93


People also ask

Can you Destructure a nested object?

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.

Can we Destructure function in JavaScript?

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.

Can we Destructure array in JavaScript?

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, ...]


1 Answers

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);
like image 114
CertainPerformance Avatar answered Nov 14 '22 23:11

CertainPerformance