Map, filter and reduce
These are native javascript functions that lets data be easily manipulated within objects or nested objects.
Map
This code is used when changing data type of the value.
In this example, an array of objects (pet bios) is transformed into a number (year born). That number is used to calculate current age in this example:
const nestedObjects = {
pet01: {
name: "Mango",
species: "Cat",
favouriteFood: ["fish", "turkey"],
yearBorn: 2020,
},
pet02: {
name: "Billy",
species: "Dog",
favouriteFood: ["everything"],
yearBorn: 2015,
},
};
// Object.values is a native javascript function. It returns an array in this example.
let petsAge = Object.values(nestedObjects).map((value) => 2025 - value.yearBorn);
Filter
This code excludes items or only includes certain items in the subsequent array (depending on how it's coded).
In this example, I filter for pets that have everything as their favourite food. I get an array of object. In this case, it would be the object nested in pet02:
const nestedObjects = {
pet01: {
name: "Mango",
species: "Cat",
favouriteFood: ["fish", "turkey"],
yearBorn: 2020,
},
pet02: {
name: "Billy",
species: "Dog",
favouriteFood: ["everything"],
yearBorn: 2015,
},
};
Object.values(nestedObjects).filter((pet) => pet.favouriteFood == "everything");
Reduce
This code is used to loop through an array of values and reduce it to one.
In this example, reduce
takes three song streams and combines it into one value (i.e. total streams).
const trackStreams = {
pleasepleaseplease: 200,
espresso: 2000,
feather: 50,
};
// reduced the array of numbers into a single number
const totalStreams = Object.values(albumListens).reduce(
(value, currentvalue) => value + currentvalue,
0
);
All notes