Arrays and Objects in ES2015

This post is 4 years old. (Or older!) Code samples may not work, screenshots may be missing and links could be broken. Although some of the content may be relevant please take it with a pinch of salt.

When working with JavaScript the two most utilised data structures are arrays and objects. (Remember, in JavaScript nearly everything is an object)

Let's first discuss how ES2015 has changed how we can work with objects – starting by one of the most interesting additions: the destructuring assignment.

Destructuring Assignment

Often times, when working with objects we want to create variables for values for certain properties in our objects. This can be achieved by utilising "dot walking" – that is – accessing the appropriate property from the object. Consider the following example:

const person = {
name: 'Steve',
age: 30,
hobbies: ['waterpolo', 'reading'],
};

const name = person.name;
console.log(name); // Steve

Now imagine that we want to also display the age property. We'd have to create another line of code and do the same that we did to retrieve the name.

The destructuring assignment allows us to extract values from objects (as well as arrays for that matter) into variables using a single line of code. Take a look at the following, this syntax is a lot cleaner:

const { name } = person; // get name OR:
const { name, age } = person; // get name and age
console.log(name, age); // Steve 30

The above example will only work if you delete one or the other variable declaration, remember you can't have the same variable name declared twice when using the const keyword

What happens when the property name is not exactly what we want to use in our code as a variable? In this case we can create an alias for the property by using the following method:

const { name: firstName } = person;
console.log(firstName); // Steve

The syntax is the following: place the object's property first, followed by a colon, followed by the desired alias.

The destructuring assignment can be similarly applied to arrays – with the exception of using aliases:

const numbers = [0, 1, 2];
const [a, b] = numbers;
console.log(a, b); // 0, 1

Array of objects and destructuring

There are many occasions when we are working with an array of objects, the destructuring operator can help us out in this case as well. Let's assume that some data comes back from an API in this format and we'd like to extract parts of it:

const response = {
count: 10,
data: [
{
name: 'Luke Skywalker',
films: ['Empire Strikes Back', 'The Force Awakens'],
},
],
};

const {
count,
data: [{ name, films }],
} = response;
console.log(count); // 10
console.log(name); // Luke Skywalker
console.log(films); // [ 'Empire Strikes Back', 'The Force Awakens' ]

If we have multiple items in the data array (that is, multiple objects), we'd have to iterate through the items, and then use the destructuring assignment:

const response = {
count: 10,
data: [
{
name: 'Luke Skywalker',
films: ['Empire Strikes Back', 'The Force Awakens'],
},
{
name: 'Han Solo',
films: ['A New Hope'],
},
],
};

const { count } = response;
console.log(count); // 10
response.data.forEach((r) => {
let { name } = r;
console.log(name); // Luke Skywalker, Han Solo
});

Property value shorthand

The next ES2015 specific addition to the JavaScript language that helps us working with objects is the property value shorthand. When working with objects we specify key-value pairs, where the value can be a value coming from a variable. This is a typical example:

const name = 'Steve';
const age = 30;

const person = {
name: name,
age: age,
};

Using the property value shorthand if we'd like our property to have the same name as the variable, we don't need to specify them using the above notation but instead we can write it in a much shorter format:

const person = {
name,
age,
};

The above is especially useful when working with Node.js's module.exports

Computed property names

One other very interesting addition that comes with ES2015 is the ability to create object properties dynamically. This means that we can now create object properties based on variables. The syntax that enables us to do this is to place an expression within []:

function nameMe(name) {
return {
[name.toLowerCase()]: {
message: `My name is ${name}`,
},
};
}

console.log(nameMe('Steve')); // {steve: {message: "My name is Steve"}}

Notice how above we not only added a computer property name but we also applied a transformation to it using the toLowerCase() method.