Dale Jefferson

Dale L. Jefferson

TypeScript, JavaScript, React, React Native

JavaScript ES8 Object.entries/values

By Dale Jefferson. Published
JavaScript, ES2017, TypeScript

JavaScript is advancing at a rapid pace. In this article, I will give a brief overview of the new Object static methods. ES8 (a.k.a 2017) now has Object.values and Object.entries to accompany Object.keys.

Object.keys

Using Object.keys to iterate over JavaScript object’s keys.

const countries = {
  FJ: "Fiji",
  CL: "Chile"
};

Object.keys(countries); // ['FJ', 'CL']

Object.values

Now we can do the same for values.

const countries = {
  FJ: "Fiji",
  CL: "Chile"
};

Object.values(countries); // ['Fiji', 'Chile']

Object.entries

But what happens if you would like to do both at the same time?

const countries = {
  FJ: "Fiji",
  CL: "Chile"
};

Object.entries(countries); // [['FJ', 'Fiji'], ['CL', 'Chile']]

Let’s map over the countries using template strings and array destructuring.

const countries = {
  FJ: "Fiji",
  CL: "Chile"
};

Object.entries(countries).map(([code, name]) => `${name} (${code})`);
// ['Fiji (FJ)', 'Chile (CL)']

Object.values and Object.entries are both available in all modern browsers and node 8.