Skip to main content

[[TOC]]

Overview


Consider this:

const tweets = [
{
id: 1080777336298049537,
message: "Hello Twitter 👋",
created_at: "2020-01-03 11:46:00",
author: {
id: 109215315,
firstName: "Solo",
lastName: "Stroup",
handle: "Soolaimon"
}
},
{
id: 1080777336298195435,
message: "Too much baseball I think",
created_at: "2021-02-19 15:32:00",
author: {
id: 109216891,
firstName: "Liz",
lastName: "Funkhouser",
handle: "LizzieF"
}
}
];

This is an array of objects, not an object itself. Knowing that this is an array, we can access properties on the array such as .forEach, .map().

// iterate over the tweets
tweets.forEach((tweet) => {
console.log(tweet.author);
});

tweets.forEach((tweet) => {
console.log(tweet.author.firstName + " " + tweet.author.lastName);
});

image.png

Always try to visualize the inner objects. Don't be afraid to run the console.log() on it via a foreach() loop or something.

Quick Recap


  • Arrays of objects are the most common data type that you will encounter when working in web development because most APIs (for example, a weather API, Twitter API, etc.) return arrays of objects.
  • A very important tip when working with arrays of objects, especially when iterating over an array of objects, is to add console.log() throughout your code to visualize the object that you receive in the callback.

Try it​


const getNumberOfTestsTaken = grades => {
return grades.length; //<-- you don't need to iterate on this one. just return the grades.length
};

// Sample usage - do not modify
const grades = [{
date: "2018-12-13",
grade: 14
}, {
date: "2018-12-15",
grade: 18
}]
console.log(getNumberOfTestsTaken(grades)); // 2

You'll need to iterate to get the first and last names of the users.

const logNames = users => {
users.forEach((user) => {
console.log(`${user.firstName} ${user.lastName}`)
});
}

// Sample usage - do not modify
const sampleUsers = [{
id: 1,
firstName: "Solo",
lastName: "Stroup"
}, {
id: 2,
firstName: "Liz",
lastName: "Funkhouser"
}];
logNames(sampleUsers); // logs: "Solo Stroup" and "Liz Funkhouser"

Totaling up parts of the array of objects​


const getSumOfGrades = results => {
let total = 0; // sets the total to 0
results.forEach((result) => { //foreach through the totals
total += result.grade; //adds the current result to the total

});
return total; //returns total

};

// Sample usage - do not modify
const results = [{
date: "2018-12-13",
grade: 14
}, {
date: "2018-12-15",
grade: 18
}]
console.log(getSumOfGrades(results)); // 32

Return the average of the two ages​


const getAverageAge = users => {
let total = 0 // sets the total to 0 for the sum of the ages
let count = users.length; // this is what you divide the total into to get the average
users.forEach(user => { //foreach through them
total += user.age //add the current iteration to the total to get the sum
})
return total / count; //return the total divided by the count
};

// Sample usage - do not modify
const users = [{
joined_on: "2018-12-13",
age: 14
}, {
joined_on: "2018-12-15",
age: 18
}];
console.log(getAverageAge(users)); // 16

Return the sum of parts of the array of objects, but what if some part is missing?​


Hint: Nullish coalescing and a lot of question marks.

const getTotalSales = users => {
let total = 0;
users.forEach(user => {
console.log(user.subscription?.info.value ?? 0) //visibility
total += user.subscription?.info.value ?? 0;
})
return total;
}

// Sample usage - do not modify
const users = [
{id: 1, name: "Alex"},
{id: 2, name: "Sam", subscription: {info: {value: 59}}},
{id: 3, name: "Charlie", subscription: {info: {value: 31}}}
];
console.log(getTotalSales(users)); // 90

Transform Arrays of Objects


In a previous example:

const names = ["solo", "Liz"];

const upperNames = names.map(name => name.toUpperCase());
console.log(upperNames); // ["SOLO", "LIZ"]

Here's how it works with an array of objects:

const tweets = [
{
id: 1080777336298049537,
message: "Hello Twitter 👋",
created_at: "2020-01-03 11:46:00"
},
{
id: 1080777336298195435,
message: "How do you keep track of your notes?",
created_at: "2021-02-19 15:32:00"
}
];

const messages = tweets.map(tweet => tweet.message);
console.log(messages);// ["Hello Twitter 👋", "How do you keep track of your notes?"]

Try it:​

const getTemperatures = recordings => {
const temperature = recordings.map((record) => record.temperature);
return temperature
}

// Sample usage - do not modify
const recordings = [{
date: "2020-01-03",
temperature: 3
}, {
date: "2020-01-04",
temperature: -4
}];
console.log(getTemperatures(recordings)); // [3, -4]

Return the names - some string concatenation here

const getFullNames = users => {
const fullNames = users.map(user => `${user.firstName.toUpperCase()} ${user.lastName.toUpperCase()}`);
return fullNames;
}

// Sample usage - do not modify
const users = [{
id: 1,
firstName: "Solo",
lastName: "Stroup"
}, {
id: 2,
firstName: "Elizabeth",
lastName: "Funkhouser"
}];
console.log(getFullNames(users)); // ["SOLO STROUP", "ELIZABETH FUNKHOUSER"]

Quick recap


  • Arrays of objects are the most common data type that you will encounter when working in web development because most APIs (for example, a weather API, Twitter API, etc.) return arrays of objects.
  • A very important tip when working with arrays of objects, especially when iterating over an array of objects, is to add console.log() throughout your code to visualize the object that you receive in the callback.