Wednesday, 12 July, 2017 UTC


Summary

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')); // '🐫'