JavaScript ES 2017: Learn Object.keys, Object.values, and Object.entries
ES 2017 introduces two new Object methods. Learn how to use them in less than three minutes in this JS Quickie
Object?
In JavaScript, an object is a collection of related data that is stored in key/value pairs. Here’s the object we’ll be working with in this tutorial. It’s an object that contains the largest cities in the world, and their respective populations:
const population = {
tokyo: 37833000,
delhi: 24953000,
shanghai: 22991000
}
As a refresher, the left entries(city names) are the keys, and the right entries (populations) are the values.
Object.keys
This method is actually not new to ES 2017, but it’s worth noting. Object.keys()
is a simple way to iterate over an object and return all of the object’s keys. Here’s how it works:
Object.keys(population);// ['tokyo', 'delhi', 'shanghai']
Object.values
Based off the above example, you can hopefully now guess what Object.values()
does. It iterates over the object and returns the object’s values! Here it is in action:
Object.values(population);// [37833000, 24953000, 22991000]
Object.entries
Why not both? Object.entries()
iterates over the Object to return both keys and values at the same time in an Array of Arrays:
Object.entries(population);// [['tokyo', 37833000],['delhi', 24953000],['shanghai', 22991000]]
Want more advanced JavaScript?
Check out: A Beginners Guide to Advanced JavaScript
I publish a few articles and tutorials each week, please consider entering your email here if you’d like to be added to my once-weekly email list.