Basically this is my Json File:
[
{
"id": 9,
"nombre": "ProductoDeJson4",
"precio": 15000,
"stock": 0,
"img": ""
},
{
"id": 10,
"nombre": "ProductoDeJson5",
"precio": 15000,
"stock": 0,
"img": ""
}
]
This is my class:
class Producto {
constructor(id, nombre, precio, stock) {
this.id = id;
this.nombre = nombre;
this.precio = precio;
this.stock = stock;
}
sumaIVA() {
this.precio *= 1.21;
}
aumentarPrecio() {
if (aumentoPrecios < 1) {
this.precio = this.precio * aumentoPrecios + this.precio;
} else {
this.precio *= aumentoPrecios;
}
}
}
And i want to do this dynamically with the data from my Json. Because i want to apply the function “aumentarPrecio()” to each one.
const producto1 = new Producto(1, "Grasa", 400, 1);
const producto2 = new Producto(2, "Desengrasante", 1000, 1);
const productos = [
producto1,
producto2,
];
Right now i’m trying to do it like this but itsn’t working. The new Producto is being created but the functions from the class aren’t working. I think it’s because i’m not creating a new const for each element from the Json. But i don’t know how to do it dynamically.
async function obtenerProductos() {
const response = await fetch("productos.json");
return await response.json();
}
let arrayProductos = obtenerProductos();
//Agrego productos del JSON al array de productos (falta agregarle los métodos o transformar cada uno en un new Producto)
arrayProductos.then((el) => {
console.log(el);
el.forEach((el) => {
console.log(el["nombre"]);
const productosJson = new Producto(
el["id"],
el["nombre"],
el["precio"],
el["stock"]
);
productos.push(productosJson);
console.log("elemento pusheado");
});
});
//Método Aumentar precio productos, luego de tener los productos listos en el array
productos.forEach((listaProductos) => {
setTimeout(() => {
listaProductos.aumentarPrecio();
console.log("precios aumentados");
}, 1000);
});
Please help me, haha. Thanks!