Iterate easily over object properties in JavaScript
//Own and enumerable properties
let simpleColors = {
colorA: 'white',
colorB: 'black'
};
let natureColors = {
colorC: 'green',
colorD: 'yellow'
};
//Example 1
Object.setPrototypeOf(natureColors, simpleColors);
console.log(Object.keys(natureColors)); // => ['colorC', 'colorD']
console.log(natureColors['colorA']); // => 'white'
console.log(natureColors['colorB']); // => 'black'
//Example 2
console.log(Object.values(natureColors));
// => ['green', 'yellow']
console.log(Object.entries(natureColors));
// => [ ['colorC', 'green'], ['colorD', 'yellow'] ]
//Example 3
let enumerableKeys = [];
for (let key in natureColors) {
enumerableKeys.push(key);
}
console.log(enumerableKeys); // => ['colorC', 'colorD', 'colorA', 'colorB']
//Object.values() returns property values
let meals = {
mealA: 'Breakfast',
mealB: 'Lunch',
mealC: 'Dinner'
};
//Example 1
for (let key of Object.keys(meals)) {
let mealName = meals[key];
console.log(mealName);
}
// 'Breakfast' 'Lunch' 'Dinner'
//Optimized Example of 1
for (let mealName of Object.values(meals)) {
console.log(mealName);
}
// 'Breakfast' 'Lunch' 'Dinner'
//Object.entries() returns pairs of property values and keys
//Example 1
for (let [key, value] of Object.entries(meals)) {
console.log(key + ':' + value);
}
// 'mealA:Breakfast' 'mealB:Lunch' 'mealC:Dinner'
// create a JavaScript object and export it into a Map
let greetings = {
morning: 'Good morning',
midday: 'Good day',
evening: 'Good evening'
};
//Example 1
let greetingsMap = new Map(Object.entries(greetings));
console.log(greetingsMap.get('morning')); // => 'Good morning'
console.log(greetingsMap.get('midday')); // => 'Good day'
console.log(greetingsMap.get('evening')); // => 'Good evening'
//Map.prototype.values() is equivalent to Object.values()
//Map.prototype.entries() is equivalent to Object.entries()
//Example 2
console.log([...greetingsMap.values()]);
// => ['Good morning', 'Good day', 'Good evening']
console.log([...greetingsMap.entries()]);
// => [ ['morning', 'Good morning'], ['midday', 'Good day'],
// ['evening', 'Good evening'] ]