In JavaScript, the most obvious way to loop through an object literal is by using a simple for...in loop. But if you like the array forEach() method, it's possible to combine it with the Object.keys() method to loop through an object's properties.

Let's imagine an object of languages that are spoken in Scandinavia. For each one, we want to print a sentence that says "In [COUNTRY], they speak [LANGUAGE]".

// Languages spoken in Scandinavia
const languages = {
denmark: 'danish',
norway: 'norwegian',
sweden: 'swedish'
};

The Object.keys() method will give us all of the keys as an array. Once we have the array, we can iterate over it using the forEach() method.

// Returns ['denmark', 'norway', 'sweden']
Object.keys(languages);

To access the values, we can use bracket notation. We'll also use our toTitleCase() helper function from last week to properly capitalize the nouns:

/**
* Convert a string to title case
* {@link https://gist.github.com/kieranbarker/293b74f1b3b46272315d2e1719786b03}
* @param {String} str The string to convert
* @returns {String} The converted string
*/

function toTitleCase(str) {
return str.toLowerCase().split(' ').map(function(word) {
return word.charAt(0).toUpperCase() + word.slice(1);
}).join(' ');
}

// Print a sentence about each country/language pair
Object.keys(languages).forEach(function(country) {
console.log(`In ${toTitleCase(country)}, they speak ${toTitleCase(languages[country])}.`);
});

Check out the demo on CodePen.