Skip to main content

Arrays and Objects in ES2015

3 min read

Older Article

This article was published 9 years ago. Some information may be outdated or no longer applicable.

The two most-used data structures in JavaScript are arrays and objects. (Remember, in JavaScript nearly everything is an object.)

Let’s start with how ES2015 changed the way we work with objects, beginning with one of the most useful additions: the destructuring assignment.

Destructuring Assignment

When working with objects, you often need to pull property values into variables. The old way: “dot walking” to grab each property. Like so:

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

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

Want the age property too? Another line of code, same pattern.

The destructuring assignment lets you extract values from objects (and arrays) in a single line. Much 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 if the property name doesn’t match the variable name you want? Create an alias:

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

The syntax: object property first, colon, then the alias.

Destructuring works on arrays too (minus the alias feature):

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

Array of objects and destructuring

Frequently you’ll be working with an array of objects. Destructuring handles that as well. Say some data comes back from an API in this format and you need 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' ]

Multiple items in the data array? Iterate first, then destructure:

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

When constructing objects, you specify key-value pairs. If the value comes from a variable with the same name as the key, you’d normally write:

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

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

The property value shorthand strips that repetition away:

const person = {
  name,
  age,
};

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

Computed property names

ES2015 also lets you create object properties dynamically, based on variables. Wrap an expression in []:

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

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

Notice how we bolted on a computed property name and applied a transformation with toLowerCase() in one go.