'How to create a new constructor with each element from my Json file. [Javascript]
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!
Solution 1:[1]
You're trying to dynamically create objects within a loop as far as i can tell.
This link might be what you are looking for.
Tldr:
- Create an empty list which will save the newly created objects
- Loop through your json as you do now but with a counter
iand extract the data for current object - Append each object to your list e.g
objects[i] = new Producto(1, "Grasa", 400, 1);(watchout here, as you are not giving your objects any name, they will be called byobject[i].function) - call your function after or during you added the objects via
object[i].aumentarPrecio()
On another note:
You probably shouldnt declare the objects as const in your code and as it might clash with your out-of-class declaration of aumentoPrecios.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
