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 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); // ["đˇ", "đŚ", "đ°"]
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')); // 'đŤ'
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