Object.keys, Object.values and Object.entries in JavaScript
Turning objects into arrays so you can loop over them.
Objects don't have map, filter or forEach like arrays do, which is a
problem when you need to loop over one. Object.keys, Object.values and
Object.entries solve this by turning an object into an array.
Each of these methods takes an object and returns an array of its keys, its values, or both.
Here's the object we'll use for every example:
const user = {name: "Pam",role: "Designer",location: "Scranton",}
Object.keys
Object.keys returns an array of the object's property names:
Object.keys(user)// ["name", "role", "location"]
A quick use for this is counting how many properties an object has:
Object.keys(user).length // 3
Object.values
Object.values returns an array of the values instead:
Object.values(user)// ["Pam", "Designer", "Scranton"]
This comes in handy for things like adding up totals:
const scores = { jim: 10, pam: 12, dwight: 8 }const total = Object.values(scores).reduce((sum, score) => sum + score, 0)// 30
Object.entries
Object.entries returns both. Each item in the array is a [key, value] pair:
Object.entries(user)// [["name", "Pam"], ["role", "Designer"], ["location", "Scranton"]]
Combined with array destructuring, this is the cleanest way to loop over an object and use both the key and the value:
Object.entries(user).forEach(([key, value]) => {console.log(`${key}: ${value}`)})// console: name: Pam// console: role: Designer// console: location: Scranton
A Practical Example
Say you need to build a query string from an object of filters. entries plus
map makes it short:
const filters = { category: "shoes", size: 10, color: "black" }const query = Object.entries(filters).map(([key, value]) => `${key}=${value}`).join("&")// "category=shoes&size=10&color=black"
Note: These methods only include the object's own enumerable properties. They skip anything inherited from the prototype, which is usually what you want.
Object.values and Object.entries aren't supported in Internet Explorer, so
add a polyfill if you still need to support it.
Have some feedback on this post? .