Skip to content
the poor coder

js get each pair of values from an array of objects

Poor Man
Published
Reading time
2 min read
On this page

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:

Text

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:

Text

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

This will output:

Text

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:

Text

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

console.log(titlesAndAuthors);

This will output:

Text

[
  { 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:

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC