JavaScript ES8 Object.entries/values

daleljefferson

Dale L. Jefferson

Posted on May 30, 2019

JavaScript ES8 Object.entries/values

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.

💖 💪 🙅 🚩
daleljefferson
Dale L. Jefferson

Posted on May 30, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related