// Tutorial //

Object.values and Object.entries in JavaScript

Published on July 12, 2017 · Updated on April 4, 2022
Default avatar
By Alligator.io
Developer and author at DigitalOcean.
Object.values and Object.entries in JavaScript

With ES2017 (ES8), the Object constructor gets two new useful methods: Object.values and Object.entries. Let’s go over their use really quickly.

Object.values

Object.values takes an object and returns an array with the values, in the same order that a for…in loop would give us. For example:

const myObj = {
  piggy: '🐷',
  birdy: '🐦',
  bunny: '🐰'
};

const myValues = Object.values(myObj); // ["🐷", "🐦", "🐰"]

Object.values doesn’t follow the prototype chain and only iterates over the value that are directly on the provided object. It won’t return any non-enumerable values either, as can be seen in this example:

const myObj = {
  piggy: '🐷',
  birdy: '🐦',
  bunny: '🐰'
};

Object.defineProperty(myObj, 'koala', {
  value: '🐨',
  writable: true,
  configurable: true,
  enumerable: true
});

let myValues = Object.values(myObj);  // ["🐷", "🐦", "🐰", "🐨"]

Object.defineProperty(myObj, 'koala', {
  value: '🐨',
  writable: true,
  configurable: true,
  enumerable: false
});

myValues = Object.values(myObj); // ["🐷", "🐦", "🐰"]

Object.entries

Very similar to the previous method, Object.entries returns an array with arrays of key-value pairs:

const moreAnimals = {
  camel: '🐫',
  boar: '🐗',
  turkey: '🦃'
};

const entries = Object.entries(moreAnimals);
// [['camel','🐫'],['boar','🐗'],['turkey','🦃']]

Since the new map object type can be initialized using an array of the shape that Object.entries gives us, it’s now very easy to create a map from an object:

const moreAnimals = {
  camel: '🐫',
  boar: '🐗',
  turkey: '🦃'
};

const animalsMap = new Map(Object.entries(moreAnimals));

console.log(animalsMap.size); // 3
console.log(animalsMap.has('turkey')); // true
console.log(animalsMap.get('camel')); // '🐫'

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Sign up
About the authors
Default avatar
Developer and author at DigitalOcean.

Still looking for an answer?

Was this helpful?
Leave a comment