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