Extract properties from JavaScript Object Destructuring

Will Johnson
InstructorWill Johnson

Share this video with your friends

Send Tweet
Published a year ago
Updated a year ago

JavaScript Destructuring assignment syntax allows you access properties from objects and name them like variables

Instructor: [0:01] Here, we have an actor object with lots of data inside of it. Let's get the first name. We'll store it in a variable. We'll go const first = actor.first(). Then let's get the second value, which will be the last name, so const last = actor.last(). We'll save that.

[0:28] Then, let's log these values to the console. Let's log first and last. Let's go to the terminal, run node will.js. We will log both values, and it will get Will Smith.

[0:44] Let's make that easier with object destructuring. We'll use the destructuring syntax, which is the curly braces. We'll use first and last. We will take those values from the actor object itself, no dot notation. Now, first and last will represent the name Will Smith. We go to the console, run node will.js. We get Will Smith logged again in a lot less code.

[1:15] Let's access the action movies with aliens and robots. We'll do const aliens, and we'll do actor.movies.action.aliens. Then we'll do const robots = actor.movies.action.robots. We'll save that.

[1:43] Let's go to the console. Let's log aliens. Let's log robots. Go to the terminal. Run node will.js. We get Men in Black and I, Robot. We have the powers of object destructuring. We can make this a lot easier. Let's delete this second line, use the destructuring syntax. We'll take out aliens and robots. Close that up.

[2:34] We don't have to go as deep. Therefore, we can delete the .aliens and just take them from action. Now, aliens and robots will represent the first two values in this nested action object.

[2:48] When we console.log aliens and robots, make sure we save that. Go to the terminal. Run node will.js. We get Men in Black and I, Robot again with a lot less code. Object destructuring makes it a lot easier to pull values out of your objects and be able to reference those values.