Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

249
Views
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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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:

  1. Create an empty list which will save the newly created objects
  2. Loop through your json as you do now but with a counter i and extract the data for current object
  3. 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 by object[i].function)
  4. 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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!