In our starter files, open the index.html page from this lessons folder:
02.Arrays-In-More-Depth > 08.Array-destructuring
ES2015 introduced destructuring which is a simple way to pull out array or object values and store them into variables.
The starter project has an array as we used previously:
let posts = [
{ title: 'How to learn Javascript', body: 'bla bla bla' },
{ title: 'How to be a ninja', body: 'bla bla bla' },
{ title: 'How to be a ninja part 2', body: 'bla bla bla' },
];
If we wanted to store each array value into a new variable, we can do this by adding destructuring.This involves modifying the variable name to be an array of names:
let [post1, post2, post3] = [
{ title: 'How to learn Javascript', body: 'bla bla bla' },
{ title: 'How to be a ninja', body: 'bla bla bla' },
{ title: 'How to be a ninja part 2', body: 'bla bla bla' },
];
This gives us three variables we can now use. We can also add the destructuring separately too.
First, if we change the name back to posts
:
let posts = [
{ title: 'How to learn Javascript', body: 'bla bla bla' },
{ title: 'How to be a ninja', body: 'bla bla bla' },
{ title: 'How to be a ninja part 2', body: 'bla bla bla' },
];
We can also set up the same result below like this:
const [post1, post2, post3] = posts;
This means we still have the destructured variables, but we also maintain the original reference to the posts
array.
And this destructuring is the same as doing something like this:
const post1 = posts[0];
const post2 = posts[1];
const post3 = posts[2];
Destructuring is just a shorter way of doing things.
Something we can also use is the JavaScript rest syntax. For example, if we just wanted to give the first object a name we could do this:
let posts = [
{ title: 'How to learn Javascript', body: 'bla bla bla' },
{ title: 'How to be a ninja', body: 'bla bla bla' },
{ title: 'How to be a ninja part 2', body: 'bla bla bla' },
];
const [post1] = posts;
We can then store all the rest of the array values into a second variable using rest. The rest syntax uses three dots, followed by a variable name:
const [post1, ...others] = posts;
This rest value should always be the last value we add inside the array.
You can now access the single post with post1
and the rest of the values with others
. This others
variable is a new array containing the rest of the remaining values:
[
{title: 'How to be a ninja', body: 'bla bla bla'},
{title: 'How to be a ninja part 2', body: 'bla bla bla'}
]
Destructuring can also be used on objects and we will cover this later, along with a closer look at rest.