js get each pair of values from an array of objects

How to Get Each Pair of Values from an Array of Objects in JavaScript

The Problem:

You have an array of objects with multiple key-value pairs and you want to iterate through each object in the array and get a specific pair of values.

The Solution:

There are a few different ways to accomplish this task in JavaScript, but one common method is to use the forEach() method to iterate through the array and then use dot notation to access the specific key-value pairs.

Let's say you have an array of objects that represents a list of books:


const books = [
  { title: 'To Kill a Mockingbird', author: 'Harper Lee' },
  { title: '1984', author: 'George Orwell' },
  { title: 'The Great Gatsby', author: 'F. Scott Fitzgerald' }
];

To get the title and author of each book, we can use the following code:


books.forEach(book => {
  console.log(book.title + ' by ' + book.author);
});

This will output:


To Kill a Mockingbird by Harper Lee
1984 by George Orwell
The Great Gatsby by F. Scott Fitzgerald

If you want to store the pairs of values in a new array, you can use the map() method:


const titlesAndAuthors = books.map(book => {
  return {title: book.title, author: book.author};
});

console.log(titlesAndAuthors);

This will output:


[
  { title: 'To Kill a Mockingbird', author: 'Harper Lee' },
  { title: '1984', author: 'George Orwell' },
  { title: 'The Great Gatsby', author: 'F. Scott Fitzgerald' }
]

Another way to accomplish this task is to use the for...of loop:


for (const book of books) {
  console.log(book.title + ' by ' + book.author);
}

This will output the same result as the forEach() method.

Conclusion:

There are multiple ways to get each pair of values from an array of objects in JavaScript, but the most common methods are using the forEach() or for...of loops to iterate through the array and dot notation to access the specific key-value pairs. The map() method can also be used to store the pairs of values in a new array.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe