How to use forEach with object in JavaScript

Oct 01, 2023#javascript

While the forEach method is frequently utilized for iterating through arrays, it is equally important to grasp its application when working with objects. In JavaScript, objects are composed of key-value pairs, and there are situations where you may need to perform operations on either their keys or values.

The term “enumerable properties” refers to those properties within an object that can be traversed using a loop or the Object.keys() method. Additionally, these properties are the ones retrieved by utilizing the Object.values() and Object.entries() methods.

The enumerable nature of properties is determined by the internal “enumerable” flag associated with each property. By default, this flag is set to true for properties created through simple assignment or property initializers.

  1. Using Object.keys() to get an array of property names. The array contains the strings that correspond to the enumerable properties found directly on the object, not on its prototype chain. The order of the array is the same as the order of the properties when looping over them with a loop.
var person = {
  name: "Alice",
  age: 25,
  occupation: "programmer"

Object.keys(person).forEach(function(key) {
  console.log(key + ": " + person[key]);

// name: Alice
// age: 25
// occupation: programmer
  1. Using Object.values() to get an array of a given object’s own enumerable string-keyed property values. This means that it takes an object as an argument and returns an array containing the values of the properties that can be looped over with a loop.
var book = {
  title: "The Hitchhiker's Guide to the Galaxy",
  author: "Douglas Adams",
  genre: "science fiction",
  rating: 4.5

Object.values(book).forEach(function(value) {

// The Hitchhiker's Guide to the Galaxy
// Douglas Adams
// science fiction
// 4.5
  1. Using Object.entries() to get an array of arrays, where each inner array contains two elements: the property key and its corresponding value.
var movie = {
  title: "The Matrix",
  director: "The Wachowskis",
  year: 1999,
  genre: "action",
  rating: 4.7

Object.entries(movie).forEach(function(entry) {
  console.log(entry[0] + ": " + entry[1]);

// title: The Matrix
// director: The Wachowskis
// year: 1999
// genre: action
// rating: 4.7