Skip to main content

Exercise 25: Obtaining Values with Object.values() and forEach()

Learn how to extract values from an object using Object.values() and manipulate them dynamically with forEach() using JavaScript. The main goal is to learn how to useObject.values()to access the values of an object and then iterate through those values withforEach()to calculate a total.

Activity

  1. Create an object that represents the price of several products, where each property is a product name and each value is the price (for example,{ manzana: 2, pera: 3, plátano: 1.5 }).

  2. UseObject.values()to obtain an array with the prices of each product.

  3. UseforEach()To add up all the prices and get the total.

  4. Print the total value on the console.

Solution

Step 1: Create the index.html file

HTML
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>
Obtener el Valor Total de los Productos con Object.values() y forEach()
</title>
</head>
<body>
<h1>
Ejercicio 25: Obtener el Valor Total de los Productos con Object.values()
y forEach()
</h1>
<p>Los cambios se muestran en consola.</p>
<script src="script.js"></script>
</body>
</html>

Step 2: Write the code in script.js

JavaScript
const productos = {
manzana: 2,
pera: 3,
platano: 1.5,
uva: 2.5,
};

const precios = Object.values(productos);

let total = 0;
precios.forEach((precio) => {
total += precio;
});

console.log("El valor total de los productos es:", total);
info

🔎Check the sectionControl instructions in JavaScriptwhere you will find more information on this topic.